作业2用两个线程玩猜数字游戏

来源:互联网 发布:i wrote python 编辑:程序博客网 时间:2024/05/17 23:47

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

package xiancheng;public class test2 {public static void main(String[] args) {Game game=new Game();game.aThread.start();;game.bThread.start();;}}class Game implements Runnable{int a,b,min=0,max=100;int flag;final int small=-1,large=1,success=0;Thread aThread,bThread;    Game() {          aThread = new Thread(this);         bThread = new Thread(this);      }   @Override  public void run() {  for (int count = 1; true; count++) {   if (Thread.currentThread() == aThread) {  if (count == 1) {     a = (int) (Math.random() * 100) + 1;     System.out.println("随机数为"+a+",猜测是多少?");    }    else {     if (a > b) {      flag = small;      System.out.println("猜小了");     }else if (a < b) {      flag =large;      System.out.println("猜大了");     }     else {      flag = success;      System.out.println("猜对了");      return;     }    }    try {     Thread.sleep(2000);    } catch (Exception e) {     e.printStackTrace();    }   }   if (Thread.currentThread() == bThread) {  if (count == 1) {     b= (min + max) / 2;     System.out.println("第" + count + "次猜:" + b);    }    else {     if (flag == small) {      min = b;      b = (min + max) / 2;      System.out.println("第" + count + "次猜:"+ b);     }     else if (flag == large) {      max = b;      b= (min + max) / 2;      System.out.println("第" + count + "次猜:"+ b);     }     else if (flag == success) {      System.out.println("成功了");      return;     }    }    try {     Thread.sleep(2000);    } catch (Exception e) {     e.printStackTrace();    }    }   }   }      }  


阅读全文
0 0