第十六周作业
题目1:编写一个应用程序,利用Java多线程机制,实现时间的同步输出显示。
package zuoyeshiyi; import java.util.*; public class xianc { public static void main(String[] args) { // TODO Auto-generated method stub new Thread(new time()).start();; } } class time implements Runnable{ public void run() { while(true) { Date nowdata=new Date(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(nowdata); } } }
题目2:编写一个应用程序,利用Java多线程机制,实现猜数字游戏(随机数范围0~100之间的整数)。
public class kkkkk { public static void main(String[] args) { Number number = new Number(); number.beicaishu.start(); number.caishu.start(); } } class Number implements Runnable { int beicainumber,caishunumber,bj; Thread beicaishu,caishu; boolean cai = false,sjshu = false; public Number() { beicaishu = new Thread(this); caishu = new Thread(this); } public void run(){ while(true) { panduan(); if(bj == 3){ return; } } } public synchronized void panduan(){ if(Thread.currentThread() == beicaishu && sjshu == false){ beicainumber = (int)(Math.random()*100) + 1; System.out.println("猜测随机数小游戏开始!" ); sjshu = true; cai = true; } if(Thread.currentThread() == beicaishu){ while(cai == true){ try { wait(); } catch (InterruptedException e) {} } if(beicainumber > caishunumber){ bj=1; System.out.println("你猜小了"); }else if (beicainumber < caishunumber){ bj=2; System.out.println("你猜大了"); }else{ bj=3; System.out.println("恭喜你,猜对了"); } cai = true; notifyAll(); } if(Thread.currentThread() == caishu){ while(cai == false){ try { wait(); } catch (InterruptedException e) {} } Scanner reader=new Scanner(System.in); if(bj == 1||bj==2){ caishunumber = reader.nextInt(); System.out.println("您输入的数是:" + caishunumber); } cai = false; } notifyAll(); } }