An interesting question about thread lock

Multithreaded lock is a very important thing. If you use it well, everything is good, if you don't use it well, everything is bad. Here is an example. If you are interested, you can leave a message to discuss it together.

Example code:

public class ShareBody {

    public void print(int count) throws Exception {
        synchronized ("123") {
            System.out.println(Thread.currentThread().getName() + "Start printing");
            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() + "Start printing");
            for (int i = 1; i < count; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            Thread.sleep(2000);
        }
    }
}

Tip: the above two classes are exactly the same except for the class name.

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: the code of the above two threads has different member variables, that is, 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, ShareBody and ShareBodyB are created. Two objects are used as shared resources by two threads.

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

Welcome to discuss

Posted on Fri, 20 Mar 2020 10:49:12 -0400 by MARIOPARTY53