Java多线程(九) synchronized 锁对象的改变

时间:2021-07-22 13:22:00
public class MyService {

    private String lock = "123";

    public void testMethod() {
        synchronized (lock) {
            System.out.println(ThreadB.currentThread().getName() + "begin " + System.currentTimeMillis());
            lock="456";
            try {
                ThreadB.sleep(2000);
                System.out.println(ThreadB.currentThread().getName() + "end " + System.currentTimeMillis());
                
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}

锁lock从“123” 改为“456”

ThreadA和ThreadB

Java多线程(九) synchronized 锁对象的改变Java多线程(九) synchronized 锁对象的改变
public class ThreadA extends Thread {

    private MyService myService;

    public ThreadA(MyService myService) {
        this.myService = myService;
    }

    public void run() {
        myService.testMethod();
    }
}

public class ThreadB extends Thread {

    private MyService myService;

    public ThreadB(MyService myService) {
        this.myService = myService;
    }

    public void run() {
        myService.testMethod();
    }
}
View Code

Run

public class Run {

    public static void main(String[] args) throws InterruptedException {
        MyService myService = new MyService();
        
        ThreadA threadA= new ThreadA(myService);
        threadA.start();
        Thread.sleep(50);
        ThreadA threadB= new ThreadA(myService);
        threadB.start();
        
    }
    
    
}

如果将Thread.sleep(50) 注释掉,A和B获取的锁都是“123”,虽然将锁改为“456”,结果还是同步的。