关于多线程中的synchronized(this)

为什么这段代码注释掉synchronized(this)程序运行后就不会一直打印。加上synchronized就会循环打印呢?
我理解这里的synchronized(this)只是锁住了线程对象本身,每个线程的对象都不一样,加不加不都是一样的么?不知道我的理解哪里出问题了,求大佬指点。以下为代码
public class OrderPrint {    private static Integer num = 1;
    static class Thread1 implements Runnable {
        @Override
        public void run() {
            while (true) {
               // synchronized (this) {
                    if (num % 3 == 1) {
                        System.out.println("Thread1: 1");
                        num++;
                    }
            //    }
            }
        }
    }
    static class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
            //    synchronized (this) {
                    if (num % 3 == 2) {
                        System.out.println("Thread2: 2");
                        num++;
                    }
          //      }
            }
        }
    }
    static class Thread3 implements Runnable {
        @Override
        public void run() {
            while (true) {
               // synchronized (this) {
                    if (num % 3 == 0) {
                        System.out.println("Thread3: 3");
                        num++;
                    }
               // }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Thread1());
        Thread thread2 = new Thread(new Thread2());
        Thread thread3 = new Thread(new Thread3());
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
回答:
可见性问题。给num加上volatile 就行了
回答:
synchronized(this) 保证了代码块里的num变量的可见性,所以可以无限打印
以上是 关于多线程中的synchronized(this) 的全部内容, 来源链接: utcz.com/p/944248.html

