我有一个类,其中有两个运行方法。其中一个在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();
}
}
我希望其他运行方法以及所有其他使用它的线程在计时器调用它的运行方法时停止。完成计时器运行方法中的作业后,我希望一切都从停止的地方继续。 我该如何做到这一点?
答案 0 :(得分:1)
听起来您不希望其他线程同时修改共享资源。您可以通过synchronizing
在线程之间访问该对象来实现。