用两个线程玩猜数字游戏,第一个线程负责随机给出1~100之间的一个整数,第二个线程负责猜出这个数。要求每当第二个线程给出自己的猜测后,第一个线程都会提示“猜小了”、“猜大了”或“猜对了”。猜数之前,要求第二个线程要等待第一个线程设置好要猜测的数。第一个线程设置好猜测数之后,两个线程还要相互等待,其原则是:第二个线程给出自己的猜测后,等待第一个线程给出的提示;第一个线程给出提示后,等待给第二个线程给出猜测,如此进行,直到第二个线程给出正确的猜测后,两个线程进入死亡状态。
package bzu;
import java.lang.Runnable;
import java.lang.Thread;
public class Test {
public static void main(String args[]) {
Number number = new Number();
number.giveNumberThread.start();
number.guessNumberThread.start();
}
}
class Number implements Runnable {
int realNumber, guessNumber, min = 0, max = 100, message;
final int SMALLER = -1, LARGER = 1, SUCCESS = 8;
Thread giveNumberThread, guessNumberThread;
Number() {
giveNumberThread = new Thread(this);
guessNumberThread = new Thread(this);
}
@Override
public void run() {
for (int count = 1; true; count++) {
if (Thread.currentThread() == giveNumberThread) {
if (count == 1) {
realNumber = (int) (Math.random() * 100) + 1;
System.out.println("随机给你一个数为" + realNumber + ",猜猜是多少");
} else {
if (realNumber > guessNumber) {
message = SMALLER;
System.out.println("你猜小了");
} else if (realNumber < guessNumber) {
message = LARGER;
System.out.println("你猜大了");
} else {
message = SUCCESS;
System.out.println("恭喜,你猜对了");
return;
}
}
try {
Thread.sleep(1500);
} catch (Exception e) {
}
}
if (Thread.currentThread() == guessNumberThread) {
if (count == 1) {
guessNumber = (min + max) / 2;
System.out.println("我第" + count + "次猜这个数:" + guessNumber);
} else {
if (message == SMALLER) {
min = guessNumber;
guessNumber = (min + max) / 2;
System.out.println("我第" + count + "次猜这个数是"
+ guessNumber);
} else if (message == LARGER) {
max = guessNumber;
guessNumber = (min + max) / 2;
System.out.println("我第" + count + "次猜这个数是"
+ guessNumber);
} else if (message == SUCCESS) {
System.out.println("我成功了");
return;
}
}
try {
Thread.sleep(1700);
} catch (Exception e) {
}
}
}
}
}
![](https://img-blog.csdn.net/20171220155915400)