码迷,mamicode.com
首页 > 编程语言 > 详细

多线程:用两个线程玩猜数字游戏......

时间:2017-12-08 13:58:13      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:ack   try   随机   数字   log   random   blog   .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) {
}
}
}
}
}

 

技术分享图片

 

多线程:用两个线程玩猜数字游戏......

标签:ack   try   随机   数字   log   random   blog   .com   技术分享   

原文地址:http://www.cnblogs.com/lyly01/p/8004818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!