-
-
-
-
-
-
package duoxiancheng;
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;
}
}
package duoxiancheng;
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();
}
}
}
}