让所有其他线程等待直到一个线程完成
Make all of other threads wait until a thread is done
我有一个class,里面有两个运行方法。其中一个在 main 方法中,它用于计时器,另一个用于其他作业和其他线程工作 with.This 是我代码的一部分:
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();
}
}
我希望另一个 运行 方法和所有其他使用它的线程在计时器调用它的 运行 方法时停止。在 timer 运行 方法中的工作完成后,我希望一切都从他们停止的地方继续。
我怎样才能做到这一点?
听起来您不希望其他线程同时修改共享资源。您可以通过 synchronizing
在线程之间访问该对象来做到这一点。
我有一个class,里面有两个运行方法。其中一个在 main 方法中,它用于计时器,另一个用于其他作业和其他线程工作 with.This 是我代码的一部分:
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();
}
}
我希望另一个 运行 方法和所有其他使用它的线程在计时器调用它的 运行 方法时停止。在 timer 运行 方法中的工作完成后,我希望一切都从他们停止的地方继续。 我怎样才能做到这一点?
听起来您不希望其他线程同时修改共享资源。您可以通过 synchronizing
在线程之间访问该对象来做到这一点。