数字游戏

来源:互联网 发布:淘宝企业店铺 企业资质 编辑:程序博客网 时间:2024/06/08 15:52
  1. 用两个线程玩猜数字游戏,第一个线程负责随机给出1~100之间的一个整数,第二个线程负责猜出这个数。 
  2.  * 要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。 
  3.  * 猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。 
  4.  * 第一个线程设置好猜测数之后,两个线程还要相互等待。 
  5.  * 其原则是:第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测。 
  6.  * 如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。 
    package 多线程;  import java.util.Random;  public class example2{              public static void main(String[] args) {                // TODO Auto-generated method stub                 guessThread fth=new guessThread();              Thread first=new Thread(fth);//正确数字线程              first.run();              while(true)                {                             try {                        Thread.sleep(10);                      guessThread sth=new guessThread();                          Thread second=new Thread(sth);                     // Thread second=new Thread(new guessThread());                      second.interrupt();  //唤醒这个进程                      second.run();                      Thread.sleep(10);                      first.interrupt();                          System.out.println("随机生成的数为"+fth.getNum()+",猜的数字为:"+sth.getNum());                    if(sth.getNum()>fth.getNum())                          System.out.println("猜大了");                                       else if(sth.getNum()<fth.getNum())                          System.out.println("猜小了");                                     else {System.out.println("猜对了");   break;}                  }                catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                 }          }  }                package 多线程;  import java.util.Random;  class guessThread implements Runnable{             int num;             public synchronized void run() {                // TODO Auto-generated method stub                Random r = new Random();                 num= r.nextInt(100);            }           public int getNum() {                return num;            }            public void setNum(int num) {                this.num = num;            }   }  

原创粉丝点击