第16周作业

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

代码:

package Example12_12;
import java.util.Date;
class ThreadTime implements Runnable{
    Date date = null;
    public void run() {
        while(true) {
        date = new Date();
        System.out.println(date);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }        
    }
} 
public class Test12_19 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread time = new Thread(new ThreadTime());
        time.start();
    }

}

运行截图:


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

代码:

package Example12_12;
import java.util.*;
class Threadnum extends Thread{
    Thread output;
     int num1,num2;
    Threadnum(){
        output = new Thread(this);
     }
    public void run() {
        Random n = new Random();
        num1 = n.nextInt(100);
        try {
            output.sleep(4000);
            Judge();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }        
    }
    public void Judge() {
        while(true){
            Scanner reader = new Scanner(System.in);
            num2 = reader.nextInt();
            if(num1==num2) {
            System.out.println("猜对了正确数字为:"+num1);
            break;
        }else if(num1>num2) {
            System.out.println("猜小了");
            
        }else {
            System.out.println("猜大了");
        }
        }
        
    }
}
public class Test12_19_2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("请输入猜测的数字");
        Threadnum num = new Threadnum();
        num.output.start();
    }

}

运行截图:

原文地址:https://www.cnblogs.com/xushaohua/p/12076559.html