An interesting question about thread locks

Multi-threaded locks are a very important thing. If you use them well, everything will be good. If you use them badly, everything will be bad. The following example, if you are interested, you can leave a message at the end of the article to discuss it together.

Example code:

public class ShareBody {

    public void print(int count) throws Exception {
        synchronized ("123") {
            System.out.println(Thread.currentThread().getName() + "开始打印");
            for (int i = 1; i < count; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            Thread.sleep(2000);
        }
    }
}
public class ShareBodyB {

    public void print(int count) throws Exception {
        synchronized ("123") {
            System.out.println(Thread.currentThread().getName() + "开始打印");
            for (int i = 1; i < count; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            Thread.sleep(2000);
        }
    }
}

Tip: The above two classes are identical except for the class names.

public class ThreadA implements Runnable {

    private ShareBody shareBody;

    public ThreadA(ShareBody shareBody) {
        this.shareBody = shareBody;
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.shareBody.print(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadB implements Runnable {

    private ShareBodyB shareBody;

    public ThreadB(ShareBodyB shareBody) {
        this.shareBody = shareBody;
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.shareBody.print(20);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Tip: In the code of the above two threads, the member variables are different, that is to say, the two threads do not share resources.

public class Main {
    public static void main(String[] args) throws Exception {
        ShareBody shareBody = new ShareBody();
        ShareBodyB shareBodyB = new ShareBodyB();

        ThreadA a = new ThreadA(shareBody);
        ThreadB b = new ThreadB(shareBodyB);

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

Tip: In the main method main, two objects, ShareBody and ShareBodyB, are created, and the two threads use the two objects as shared resources.

So here comes the question: what will the output look like? Will two threads cross output? Or is it synchronous output (after one thread finishes output, another thread outputs again)?

Welcome to the discussion

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325308819&siteId=291194637