简体   繁体   English

让所有其他线程等到一个线程完成

[英]Make all of other threads wait until a thread is done

I have one class and there are two run methods in it.我有一个 class ,其中有两种运行方法。 one of them is in main method and it's for timer and the other is for other jobs and other threads to work with.This is a part of my code:其中一个在 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();

        
    }
}

I want the other run method and all other threads that are using it to stop when the timer calls it's run method.当计时器调用它的运行方法时,我希望其他运行方法和所有其他使用它的线程停止。 after the job in timer run method is done I want everything to continue from where they stopped.在计时器运行方法中的工作完成后,我希望一切从他们停止的地方继续。 how can I make this happen?我怎样才能做到这一点?

It sounds like you don't want other threads modifying a shared resource at the same time.听起来您不希望其他线程同时修改共享资源。 You can do this by synchronizing access to that object between threads.您可以通过在线程之间synchronizing对 object 的访问来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM