第16周作业
题目1:
编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
代码:
时间显示类:
1 package 多线程作业; 2 3 import java.util.Date; 4 5 public class TimeShow extends Thread { 6 7 public void run() { 8 super.run(); 9 Date date; 10 while(true){ 11 date = new Date(); 12 System.out.println(date); 13 try { 14 date = new Date(); 15 System.out.println(date); 16 Thread.sleep(1000); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 22 23 24 } 25 26 27 28 }
测试类:
1 package 多线程作业; 2 3 public class Test { 4 5 public static void main(String[] args) { 6 7 TimeShow ts= new TimeShow(); 8 ts.start(); 9 10 } 11 12 }
截图:

题目2:
编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
代码:
Bulls_Cows类:
1 package com.ccut.thread; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 6 /** 7 * 该类继承Runnable接口,实现run方法。 8 * 9 */ 10 public class Bulls_Cows implements Runnable { 11 Thread t1, t2; 12 Option op; 13 Scanner scan; 14 15 public Bulls_Cows() { 16 t1 = new Thread(this); 17 t2 = new Thread(this); 18 op = new Option(); 19 20 } 21 22 public void run() { 23 if (Thread.currentThread() == t1) { 24 while (true) { 25 op.CompareR_N(); 26 try { 27 Thread.sleep(2000); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 } 32 } else if (Thread.currentThread() == t2) { 33 while (true) { 34 op.Comp(); 35 } 36 } 37 38 } 39 }
Option类:
1 package com.ccut.thread; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 /** 6 * 两个同步方法,一个控制每次猜对后更改随机数,另一个控制没猜对继续猜 7 * 8 */ 9 public class Option { 10 Scanner scanner = new Scanner(System.in); 11 Random rd = new Random(); 12 int random, num; 13 14 int getNum() { 15 return scanner.nextInt(); 16 } 17 18 int getRandom() { 19 return rd.nextInt(); 20 } 21 22 synchronized void CompareR_N() { 23 random = rd.nextInt(100); 24 try { 25 Thread.sleep(1000); 26 } catch (InterruptedException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 notifyAll(); 31 } 32 33 synchronized void Comp() { 34 num = this.getNum(); 35 while (num != random) { 36 if (num < random) 37 System.out.println("猜小了,请重新猜"); 38 else 39 System.out.println("猜大了,请重新猜"); 40 num = this.getNum(); 41 } 42 System.out.println("猜对了,数字已更换"); 43 try { 44 wait(); 45 } catch (InterruptedException e) { 46 e.printStackTrace(); 47 } 48 } 49 50 }
测试类:
1 package com.ccut.thread; 2 /** 3 * 4 *测试类 5 */ 6 public class Test { 7 public static void main(String[] args) { 8 Bulls_Cows bc = new Bulls_Cows(); 9 System.out.println("开始猜数字游戏"); 10 11 bc.t1.start(); 12 bc.t2.start(); 13 } 14 }
截图:


浙公网安备 33010602011771号