【发布时间】:2020-07-19 19:22:31
【问题描述】:
我有一个类,其中有两个运行方法。其中一个在 main 方法中,用于计时器,另一个用于其他作业和其他线程。这是我代码的一部分:
public void run() {
while (!exit) {
if (!isFirstTime) {
System.out.println("FIRST TIME RUN Starting Thread " +
Thread.currentThread().getId() +
" is running");
isFirstTime = true;
try {
firstTimePosses();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(1000);
System.out.println("RUN Starting Thread " +
Thread.currentThread().getId() +
" is running");
posses();
// Displaying the thread that is running
} catch (Exception e) {
System.out.println("Exception Caught");
}
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("The game begins!");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("IF A YOU WANT TO CHANGE A PLAYER PRESS 1 OTHERWISE JUST PRESS 2");
Scanner input = new Scanner(System.in);
int wantSub = input.nextInt();
}
}, 30, 3000);
Players.threads[0].start();
}
}
当计时器调用它的 run 方法时,我希望其他 run 方法和所有其他使用它的线程停止。在计时器运行方法中的工作完成后,我希望一切从他们停止的地方继续。 我怎样才能做到这一点?
【问题讨论】:
-
听起来你想interrupt一些线程。也请考虑发布minimal reproducible example,以便人们更轻松地为您提供帮助。
-
您为什么将
synchronized添加到main? ^^
标签: java multithreading synchronization locking java-threads