gpt4 book ai didi

java - 确保两个线程依次循环 - Android

转载 作者:行者123 更新时间:2023-12-01 19:59:23 37 4
gpt4 key购买 nike

我有两个像这样开始的线程

    Thread player1Thread = new Thread(new Player1RunnableManual());
player1Thread.start();
Thread player2Thread = new Thread(new Player2RunnableManual());
player2Thread.start();

两个玩家(玩家 1 和玩家 2)以不同的方式猜测 100 个数字,一次一个。我们可以忽略他们使用什么启发式来猜测数字。我需要确保player1先运行,然后player2运行,然后player1运行,然后再次运行player2,直到其中一个猜测到特定数字(硬编码)。

我尝试使用可重入锁,但无法使其工作。玩家 1 和玩家 2 的可运行对象如下。

如何编写锁实现代码以使其正常工作?

class Player1RunnableManual implements Runnable {
@Override
public void run() {
while (!gopherFound) {
r = new Random();
final int player1Position = r.nextInt(high - low) + low;
final int outcome = calculateProximity(player1, player1Position);
if (outcome != DISASTER) {
runnableHandler.post(new Runnable() {
@Override
public void run() {
if (holes[player1Position] == 0) {
setPosition(player1, player1Position);
player1Status.setText(outcomesList[outcome]);
}
}
});
if (outcome == SUCCESS) {
gopherFound = true;
winner = "Player 1";
result.setText("Player 1 wins");
break;
}
}
try {
int sleep = r.nextInt(threadHigh - threadLow) + threadLow;
Thread.sleep(sleep);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
}


class Player2RunnableManual implements Runnable {

@Override
public void run() {
for (int i = 1; i <= 100 && !gopherFound; i++) {
final int player2Position = i;
final int outcome = calculateProximity(player2, player2Position);
if (outcome != DISASTER) {
Message msg = messageHandler.obtainMessage(player2);
msg.arg1 = player2Position;
msg.arg2 = outcome;
messageHandler.sendMessage(msg);
if (outcome == SUCCESS) {
gopherFound = true;
winner = "Player 2";
result.setText("Player 2 wins");
break;
}
}
try {
int sleep = r.nextInt(threadHigh - threadLow) + threadLow;
Thread.sleep(sleep);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
}

最佳答案

为什么不使用单线程执行器?可运行对象将被排队。

Executor executor = Executors.newSingleThreadExecutor();
while(!gopherFound){
executor.execute(new Player1RunnableManual());
executor.execute(new Player2RunnableManual());
// wait here for the end of the 2 runnables, maybe using Future tasks instead of runnables
}

你可以清理代码,runnables 内部不能再有“while (!gopherFound)”,但是有了这个,你就可以确定 runnables 是一个接一个执行的

另一种方法是使用“Semaphore(1)”,也可以使用“acquire()”和“release()”方法来完成这项工作,但它不能保证哪个线程将首先执行。

关于java - 确保两个线程依次循环 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59014236/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com