用两个线程玩猜数字游戏.

来源:互联网 发布:windows下nginx配置 编辑:程序博客网 时间:2024/05/03 09:09

用两个线程玩猜数字游戏,第一个线程负责随机给出1~100之间的一个整数,第二个线程负责猜出这个数。要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。第一个线程设置好猜测数之后,两个线程还要相互等待,其原则是:第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测,如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。

package dxc;import java.util.Random;public class cai {public static void main(String []args){caiThread fnum=new caiThread();Thread first = new Thread(fnum);first.run();while(true){try{Thread.sleep(10);caiThread snum=new caiThread();Thread second =new Thread(snum);second.interrupt();second.run();Thread.sleep(10);first.interrupt();System.out.println("随机生成的数是"+fnum.getNum()+",猜的数字是"+snum.getNum());if(snum.getNum()>fnum.getNum())System.out.println("猜打了!");else if(snum.getNum()<fnum.getNum())System.out.println("猜小了!");else{System.out.println("终于猜对啦!");break;}}catch(InterruptedException e){e.printStackTrace();}}}}package dxc;import java.util.Random;class caiThread implements Runnable{int num;public synchronized void run(){Random r=new Random();num=r.nextInt(100);}public int getNum(){return num;}public void setNum(int num){this.num=num;}}


阅读全文
0 0
原创粉丝点击