Search code examples
javamultithreadingsynchronizationlockingjava-threads

Make all of other threads wait until a thread is done


I have one class and there are two run methods in it. 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:

    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?


Solution

  • 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.