基本上我想在调用方法之后暂停我的线程,然后继续执行另一个方法。我无法循环,我的方法只能运行一次。 这个想法背后,是用在游戏中,方法将显示消息,并且每当用户按下一个键时,就会显示下一条消息。我不能仅仅通过一个列表,因为游戏需要用户输入。我看着Thread.pause()
和Thread.resume()
但他们不会工作,并已弃用。 我当前的代码(这是不工作):在调用方法后暂停线程
private Thread thread;
private Thread managerThread;
private final Object lock = new Object();
private boolean shouldThreadRun = true;
private boolean storyRunning = true;
public Storyline() {
setUpThread();
}
private void setUpThread() {
managerThread = new Thread(() -> {
while(storyRunning) {
synchronized (lock) {
if(!shouldThreadRun) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Looping");
}
}
});
thread = new Thread(() -> {
synchronized (lock) {
pauseThread();
System.out.print("A");
pauseThread();
System.out.print("B");
}
});
managerThread.start();
thread.start();
}
public void pauseThread() {
shouldThreadRun = false;
}
public void resumeThread() {
shouldThreadRun = true;
}
你不会在我看到的任何地方调用'resumeThread()'。另外,如果要由不同的线程修改和读取'shouldThreadRun',则应声明'volatile'。 –
https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html –
因为我正在测试以查看'B'是否打印过,因为它不应该打印。但它确实被打印 –