分析:该案例和案例4一样,添加对象锁,只能保证同一对象的并发同步,不能保证不同对象同步。
7. 静态变量+同步代码块+类锁 public class SynDemo implements Runnable { private static int sum = 0; @Override public void run() { add(); } private void add() { synchronized (SynDemo.class) { for (int i = 0; i < 1000; i++) { sum++; } } } public static void main(String[] args) throws InterruptedException { SynDemo sync01 = new SynDemo(); Thread thread1 = new Thread(sync01); Thread thread2 = new Thread(sync01); thread1.start(); thread2.start(); thread1.join(); //等待线程执行完 thread2.join(); //等待线程执行完 System.out.println(sum); } } result: 2000 public class SynDemo implements Runnable { private static int sum = 0; @Override public void run() { add(); } private void add() { synchronized (SynDemo.class) { for (int i = 0; i < 1000; i++) { sum++; } } } public static void main(String[] args) throws InterruptedException { SynDemo sync01 = new SynDemo(); SynDemo sync02 = new SynDemo(); Thread thread1 = new Thread(sync01); Thread thread2 = new Thread(sync02); thread1.start(); thread2.start(); thread1.join(); //等待线程执行完 thread2.join(); //等待线程执行完 System.out.println(sum); } } result: 2000分析:
该案例同案例5一样,添加类锁,无论是多个线程操作一个实例化对象还是多个实例化对象,都能保证线程安全。
总结:
对象锁只能保证各自实例化对象并发的线程安全问题。类锁可以保证多个实例化多谢的安全问题。