多线程:用两个线程玩猜数字游戏......
Posted 呓亿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程:用两个线程玩猜数字游戏......相关的知识,希望对你有一定的参考价值。
package Thread11;
public class Guess {
public static void main(String[] args) {
// TODO 自动生成的方法存根
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() {
// TODO Auto-generated method stub
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(1500);
} catch (Exception e) {
}
}
}
}
}
以上是关于多线程:用两个线程玩猜数字游戏......的主要内容,如果未能解决你的问题,请参考以下文章