Java练习题24 猜数字

来源:互联网 发布:windows快速打开程序 编辑:程序博客网 时间:2024/06/03 18:11

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

import java.util.Random;public class Test {static class Caishuzi implements Runnable{int n;public void run(){synchronized(this){Random r = new Random();                n= r.nextInt(100);}}public int getNum() {                return n;            }            public void setNum(int n) {                this.n=n;            }public void interrupt() {}   }public static void main(String[] args) {Caishuzi shuzi1=new Caishuzi();new Thread(shuzi1,"xiancheng1");shuzi1.run(); while(true)             {                          try {                     Thread.sleep(10);                   Caishuzi shuzi2=new Caishuzi();                 new Thread(shuzi2,"xiancheng2");                  shuzi2.interrupt();                 shuzi2.run();                   Thread.sleep(10);                   shuzi1.interrupt();                       System.out.println("随机生成数:"+shuzi1.getNum()+",猜数字为:"+shuzi2.getNum());                 if(shuzi2.getNum()>shuzi1.getNum())                       System.out.println("猜大了!");                  else if(shuzi2.getNum()<shuzi1.getNum())                      System.out.println("猜小了!");                               else{             System.out.println("猜对了!");             break;             }               }                catch (InterruptedException e) {                  e.printStackTrace();                }              }       }  }