线程同步机制-多个对象使用多个对象锁
代码如下: public class Demo03 { public static void main(String[] args) { **Demo03Service service1 = new Demo03Service();** **Demo03Service service2 = new Demo03Service();** **Thread threadB = new Demo03ThreadB(service1);** **Thread threadA = new Demo03ThreadA(service2);** threadB.start(); threadA.start(); } } class Demo03Service{ private int num; synchronized public void add(String userName){ if(Objects.equals("a",userName)){ num=100; System.out.println("a is set"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }else { num=200; System.out.println("b is set"); } System.out.println("userName="+userName+", num="+num); } } class Demo03ThreadA extends Thread{ private Demo03Service service; public Demo03ThreadA(Demo03Service service){ this.service=service; } @Override public void run() { service.add("a"); } } class Demo03ThreadB extends Thread{ private Demo03Service service; public Demo03ThreadB(Demo03Service service){ this.service=service; } @Override public void run() { service.add("b"); } }
运行结果:
可以看出线程A在睡眠的时候,B线程也在执行,两个线程并不是同步执行,结果数据都正确。是因为线程作用于不同的对象使用多个锁,两个线程对彼此的锁都不影响。