十六次作业

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

 1 package shiliu;
 2 import java.util.Date;
 3 public class duoxiancheng {
 4     public static void main(String[] args) {
 5         ThreadTime time = new ThreadTime();
 6         time.start();        
 7     }
 8 }
 9  class ThreadTime extends Thread {
10     public void run() {
11         Date riqi = new Date();       
12         while (true) {
13             riqi = new Date();
14             System.out.println(riqi);
15             try {
16                 Thread.sleep(1000);
17             }catch (InterruptedException a) {
18                 a.getStackTrace();
19             }
20         }     
21     }
22 }

十六次作业_第1张图片

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

 1 package shiliu;
 2 import java.util.*;
 3 public class caishuzi {
 4     public static void main(String[] args) {
 5         System.out.println("猜数字游戏现在开始!!!");
 6         System.out.println("请输入一个0-100之间的数字:");
 7         Scanner a = new Scanner(System.in);
 8         Thread shu1 = new Thread();
 9         Thread t = new Thread(shu1);
10         t.start();        
11         try {
12             Thread.sleep(100);
13             while(true){
14                 int shu2 =a.nextInt();
15                 if(shu1.getId()>shu2){
16                     System.out.println("数字偏小,请重新输入");
17                     break;
18                 }
19                 else if(shu1.getId()==shu2){
20                     System.out.println("哈哈!恭喜你答对啦!!!");
21                 }
22                 else{
23                     System.out.println("数字偏大,请重新输入");
24                 }
25             }
26             
27             
28         } catch (InterruptedException e) {
29             e.printStackTrace();
30         }
31 
32     }
33 
34 }
35 class Num implements Runnable{
36     int num;
37     public synchronized void run() {
38         Random n= new Random();
39         num=n.nextInt(100);
40     }
41     public int getNum() {
42         return num;
43     }
44     public void setNum(int num) {
45         this.num=num;
46     }
47 }

十六次作业_第2张图片

你可能感兴趣的:(十六次作业)