第16周作业

题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。

题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)

package sixteen;
import java.util.Date;
/**
 * 编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
 */
class ThreadMethod implements Runnable{
    Thread time;
    ThreadMethod(){
        time=new Thread(this);
    }
    @Override
    public void run() {
        while(true){
            Date nowTime=new Date();
            System.out.println(nowTime);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class TimeThread {
    public static void main(String[] args) {
        ThreadMethod t=new ThreadMethod();
        t.time.start();
    }
}
package sixteen;
import java.util.Random;
import java.util.Scanner;
/**
 * 编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)
 */
class FigThread implements Runnable{
    Thread num,guess;
    int number,random;
    Scanner s=new Scanner(System.in);
    Random ran=new Random();
    FigThread(){
        num=new Thread(this);
    }
    int getNumber() {
        return s.nextInt();
    }
    @Override
    public void run() {
        if (Thread.currentThread()==num){
            random = ran.nextInt(100);
            try {
                guess=new Thread(this);
                guess.start();
                Thread.sleep(1000*60*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else if (Thread.currentThread()==guess){
            number = this.getNumber();
            while(number!=random){
                if (number>random){
                    System.out.println("big");
                }else if (number<random){
                    System.out.println("small");
                }
                number = this.getNumber();
            }
            System.out.println("yes");
        }
    }
}
/**
 * @author WH
 */
public class NumberThread {
    public static void main(String[] args) {
        System.out.println("输入0~100的数字:");
        FigThread r=new FigThread();
        r.num.start();
    }
}

posted on 2019-12-22 22:14  Amiri-BOY  阅读(111)  评论(0编辑  收藏  举报

导航