展开全部
package practice12;
/**
* @Author: HuDaoquan
* @Description: TODO
* @Email: hudaoquan@enn.cn
* @Date: 2020-6-20 1:01
* @Version 1.0
*/
public class Number implements Runnable {
final int SMALLER = -1, LARGER = 1, SUCCESS = 888;
int realNumber, guessNumber, min = 0, max = 100, message = SMALLER;
boolean pleaseGuess = false, isGiveNumber = false;
Thread giveNumberThread, guessNumberThread;
Number() {
giveNumberThread = new Thread(this);
guessNumberThread = new Thread(this);
}
@Override
public void run() {
for (int count = 1; count < 10; count++) {
System.err.println(count + " " + message + Thread.currentThread().getName());
setMessage(count);
if (message == SUCCESS) {
return;
} else {
continue;
}
}
}
public synchronized void setMessage(int count) {
if (Thread.currentThread() == giveNumberThread && isGiveNumber == false) {
realNumber = (int) (Math.random() * 100 + 1);
System.out.println("我在心里想了一个1-100的数,你猜猜看,它是多少32313133353236313431303231363533e58685e5aeb931333433636163?====" + realNumber);
isGiveNumber = true;
// 让下面的判断语句执行猜线程
pleaseGuess = true;
}
if (Thread.currentThread() == giveNumberThread && isGiveNumber == true) {
//pleaseGuess为true,调用猜线程,猜线程将pleaseGuess置为false,结束循环,也就是在此调用猜线程
while (pleaseGuess == true) {
try {
wait();
// 猜线程执行完,猜线程将pleaseGuess置为false,下一次循环退出while,执行后续if语句
} catch (InterruptedException e) {
}
}
// 调用完一次猜,开始判断猜的结果并给出message信息
if (realNumber > guessNumber) {
message = SMALLER;
System.out.println(guessNumber + "你猜小了,大点试试!");
} else if (realNumber < guessNumber) {
message = LARGER;
System.out.println(guessNumber + "你猜大了,小点试试");
} else {
message = SUCCESS;
System.out.println(guessNumber + "太棒啦,你猜对了呢");
}
// 给完信息,将pleaseGuess置为true,给猜线程调用的时候退出wait;也就是开始猜
pleaseGuess = true;
}
if (Thread.currentThread() == guessNumberThread && isGiveNumber == true) {
// 读到猜线程为false,则调用wait,停止猜,调用给线程
while (pleaseGuess == false) {
try {
wait();
// 给线程执行完会将pleaseGuess置为true,此处下一次循环即会结束wait调用,执行后续语句
} catch (InterruptedException e) {
}
}
// 开始猜
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);
}
pleaseGuess = false;
}
notifyAll();
}
public static void main(String[] args) {
Number number = new Number();
number.giveNumberThread.start();
number.guessNumberThread.start();
}
}
代码截图
运行结果