题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
/*使用Runnable接口使用类创建线程对象,重写run()方法**/
代码
1public class timetext { 2 3 4 public static void main(String[] args) { 5 Thread thread =new Thread(new time()); 6 thread.start(); 7 8 } 9 10} 11 12import java.util.Date; 13 14 15public class time implements Runnable { 16 17 public void run() { 18 Date date =null; 19 while(true){ 20 date=new Date(); 21 System.out.println(date); 22 try { 23 Thread.sleep(1000); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } 27 } 28} 29 30}
运行结果

编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
代码
1public class Test { 2 3 4 public static void main(String[] args) { 5 game ga=new game(); 6 ga.rand.start(); 7 ga.input.start(); 8 9 } 10 11} 12 13import java.util.*; 14public class game implements Runnable { 15 Thread rand,input; 16 int inputnum,random,flag; 17 boolean a=false,b=false; 18 public game(){ 19 rand=new Thread(this); 20 input=new Thread(this); 21 } 22 23 public void run() { 24 while(true){ 25 compare(); 26 if(flag==3) 27 return; 28 } 29 } 30 public synchronized void compare(){ 31 if(Thread.currentThread()==rand&&b==false){ 32 random=(int)(Math.random()*100)+1; 33 System.out.println("猜数游戏开始!"); 34 a=true; 35 b=true; 36 } 37 if(Thread.currentThread()==rand){ 38 if(a==true){ 39 try { 40 wait(); 41 } catch (InterruptedException e) { 42 43 e.printStackTrace(); 44 } 45 } 46 if(inputnum<random){ 47 System.out.println("猜小了!请重猜!"); 48 flag=1; 49 } 50 else if(inputnum>random){ 51 System.out.println("猜大了!请重猜!"); 52 flag=2; 53 } 54 else if(inputnum==random){ 55 System.out.println("恭喜您猜对了!"); 56 flag=3; 57 } 58 a=true; 59 notifyAll(); 60 61 } 62 if(Thread.currentThread()==input){ 63 while(a==false){ 64 try { 65 wait(); 66 } catch (InterruptedException e) { 67 68 e.printStackTrace(); 69 } 70 } 71 if(flag<3){ 72 System.out.println("请输入您猜的数!"); 73 Scanner r=new Scanner(System.in); 74 inputnum=r.nextInt(); 75 } 76 a=false; 77 } 78 notifyAll(); 79 } 80 81}
运行结果
