1

Can someone help me how we can synchronize the java multi-threading programe below I am learning Multi-thread in java which is a bit complex subject and i got this problem online and tried to solve it but i cant.

    public class GoMyThread {
        public static void main(String[] args) {
            MyThread t1 = new MyThread("Louis");
            MyThread t2 = new MyThread("Mathilde");
            MyThread t3 = new MyThread("Toto");
            t1.start();
            t2.start();
            t3.start();
        }
    }


    public class MyThread extends Thread {

        public MyThread(String name) {
            super(name);

        }

        public  void run() {
        for (int i = 0; i < 3; i++)
            {
                System.out.println(getName() + " Finish , level  " + (i+1));
                if (getName().compareTo("Louis") != 0)
                {
                    try{
                        Thread.sleep(100);
                    }
                    catch (InterruptedException e){}
                }
            }
        }

    }                  
 the out put for this is of the programe changes with every run 

for example ,the output below is one of them

    Louis Finish , level  1
    Louis Finish , level  2
    Louis Finish , level  3
    Toto Finish , level  1
    Mathilde Finish , level  1
    Toto Finish , level  2
    Mathilde Finish , level  2
    Toto Finish , level  3
    Mathilde Finish , level  3 

  what I want is  the output to be  like ,three of them finish level 1 before passing to the next level ,But i can't achieve it no matter i try ,the 

output must look like below.

    Louis Finish , level  1`
    Mathilde Finish , level  1
    Toto Finish , level  1
    Louis  Finish , level  2
    Toto Finish , level  2
    Mathilde Finish , level  2
    Toto Finish , level  3
    Mathilde Finish , level  3                                                                                  
    Louis  Finish,level  3                                                                                                   

 I  will appriciate if you give me some concepts to understand java Thread programming  too , ,Thank You! 
3
  • if (getName().compareTo("Louis") != 0) - Why is that necessary? Commented Nov 24, 2018 at 12:36
  • @Joe yea you write it is not necessary ,i was playing with programe and i forget it ,but we dont need it to solve the problem Commented Nov 24, 2018 at 13:05
  • You can use a cyclicbarrier for this kind of problem. Just pass the same barrier to every thread and call await on the barrier. This way the only can continue until everyone arrived at the barrier. Source: baeldung.com/java-cyclic-barrier Commented Nov 24, 2018 at 14:31

2 Answers 2

1

Threads are running in parallel by nature so the fact that you get different results every time you run the program is the normal behavior.

There are ways though where you can force them to run in some kind of order, like t1 you will start executing after t2 is done, etc...

what I want is the output to be like ,three of them finish level 1 before passing to the next level ,But i can't achieve it no matter i try ,the

output must look like below.

Louis Finish , level  1`
Mathilde Finish , level  1
Toto Finish , level  1
Louis  Finish , level  2
Toto Finish , level  2
Mathilde Finish , level  2
Toto Finish , level  3
Mathilde Finish , level  3                                                                                  
Louis  Finish,level  3

If you want that then give them some time for the other competitors to reach the same level. Here is the code:

public class GoMyThread {
    public static void main(String[] args) {
            MyThread t1 = new MyThread("Louis");
            MyThread t2 = new MyThread("Mathilde");
            MyThread t3 = new MyThread("Toto");
            t1.start();
            t2.start();
            t3.start();
    }

    static class MyThread extends Thread {

        public MyThread(String name) {
            super(name);
        }

        public  void run() {
            for (int i = 0; i < 3; i++){
                    System.out.println(getName() + " Finish , level  " + (i+1));
                    try{
                        // Force a sleep to give the other threads time to reach the same level
                        Thread.sleep(500);
                    }catch (InterruptedException e) {
                        System.out.println("Something went wrong with sleep");
                    }

                    if (getName().compareTo("Louis") != 0){
                        try{
                            Thread.sleep(100);
                        }
                        catch (InterruptedException e){}
                    }
            }
        }
    }
}

The result will always be what you want because 500 milliseconds of waiting is like a whole day passing for a thread.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you , it works but do we really need the static class modifier in the second class?
First of all when an answer is correct, be kind and mark it as correct. Secondly no, you don't need the static class modifier in the second class. You had MyThread defined outside of GoMyThread, I put it inside and defined it as staticjust to call it directly in your main().
Sorry, I have marked it as correct ,my dumb ass didn't even know you should mark as correct if it works .
There's nothing to be sorry about. You give thumbs up if you believe this answer was useful. Now if you were the once that you've asked, like now, you are the one who has the right to mark it as correct. If someone views your question he (usually) checks first the correct one.
Also by doing that you gain reputation, the one who answer receives as well and if you ask a question in the future and really need an answer, you can 'sacrifice' some of your reputation to attract other to answer it.
0

You can use a static counter for the number of threads, and add a while loop after printing the level to check if the number of loops is reached. You can also use shared CountDownLatch, but you’ll have to reset it (create a new one) after each level.

2 Comments

can we solve it with synchronization, wait(),notify()..?
Yes, and it’s a better solution than using while and sleep, but you’ll have to count the number of threads that reached the level again before notifyAll().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.