简体   繁体   中英

I don't understand how synchronization works in my code

I have a question regarding multythreading and specifically synchronization. I've created a Runnable that adds two numbers entered by the user, but their outputs are mixed up.

I've tried synchronizing on the method that the Runnable calls. This didn't work (I believe it has to do with the Threads being different objects thus not using the same instance of the method)... I then tried to synchronize on one of the objects but that also didn't give the desired result.

Could somebody please explain what is happening? See the code below:

public static void main(String[] args) {
    Thread a = new Thread( new <CLASSNAME>, "Thread A"); 
    Thread b = new Thread( new <CLASSNAME>, "Thread B"); 

    synchronized (a) {
        a.start(); 
    }
    synchronized (a) {
        b.start(); 
    }
}

This gives a result like

Thread A: <INPUT PROMPT 1>
Thread B: <INPUT PROMPT 1>
Thread B: <INPUT PROMPT 2>
Thread A: <INPUT PROMPT 2>

Thread A: <OUTPUT>
Thread B: <OUTPUT>

I get that this problem could be solved using the join method, but I would also like to know why the synchronization failed. Does it have to do anything with the fact that I don't actually try to do something with Thread a in the synchronization of Thread b ?

I've added some comments to your code to explain:

public static void main(String[] args) {
        Thread a = new Thread( new <CLASSNAME>, "Thread A");
        Thread b = new Thread( new <CLASSNAME>, "Thread B");

        // synchronize all threads call 'a.start()'
        // but in this case, only main thread call
        // so 'synchronized' is unnecessary
        synchronized (a) {
            a.start();
        }

        // synchronize all threads call 'b.start()'
        // but in this case, only main thread call
        // so 'synchronized' is unnecessary
        synchronized (a) {
            b.start();
        }
}

equals to:

public static void main(String[] args) {
        Thread a = new Thread( new <CLASSNAME>, "Thread A");
        Thread b = new Thread( new <CLASSNAME>, "Thread B");

        a.start();
        b.start();
}

please read this guide to learn more about Java Synchronization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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