thread两个线程交替运行,在线等!!!!

//当前线程代码publicclassGuessNumberimplementsRunnable{privateStringplayerName;//玩家名字privat... //当前线程代码

public class GuessNumber implements Runnable {
private String playerName;//玩家名字
private GiveNumber giveNumber;//游戏对象

public GuessNumber(String playerName , GiveNumber giveNumber) {
this.playerName = playerName;
this.giveNumber = giveNumber;
}

@Override
public void run() {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.print(playerName + " 猜:");
int nowNum = sc.nextInt();
System.out.println("你猜的数字是" + nowNum);
}
}

}

//在另一个类中运行这个线程
public class StartGame {

public static void main(String[] args) throws InterruptedException {
GiveNumber giveNumber = new GiveNumber();
GuessNumber guessNumber1 = new GuessNumber("玩家1", giveNumber);
GuessNumber guessNumber2 = new GuessNumber("玩家2", giveNumber);
Thread thread1 = new Thread(guessNumber1);
Thread thread2 = new Thread(guessNumber2);
thread1.start();
thread2.start();
}

}

问题,我怎么让两个线程thread1和thread1交替运行,要求用到 wait notify
展开
 我来答
匿名用户
推荐于2017-09-27
展开全部
public class GuessNumber implements Runnable {
private String playerName;//玩家名字
private Object giveNumber;//游戏对象

public GuessNumber(String playerName , Object giveNumber) {
this.playerName = playerName;
this.giveNumber = giveNumber;
}

@Override
public void run() {
while (true) {
synchronized (giveNumber) {
Scanner sc = new Scanner(System.in);
System.out.print(playerName + " 猜:");
int nowNum = sc.nextInt();
System.out.println("你猜的数字是" + nowNum);
giveNumber.notify();
try {
giveNumber.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Object giveNumber = new Object();
GuessNumber guessNumber1 = new GuessNumber("玩家1", giveNumber);
GuessNumber guessNumber2 = new GuessNumber("玩家2", giveNumber);
Thread thread1 = new Thread(guessNumber1);
Thread thread2 = new Thread(guessNumber2);
thread1.start();
thread2.start();
}

}

我这没有GiveNumber 这个类,你把Object替换了就行
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式