美文网首页
同步synchronized方法无限等待与解决

同步synchronized方法无限等待与解决

作者: 迷糊小生 | 来源:发表于2019-03-28 09:05 被阅读0次
public class Service {

    public synchronized void printA() {
        System.out.println("printA begain");
        while (true) {
        }
    }
    
    public synchronized void printB() {
        System.out.println("printB begain");
        System.out.println("printB end");
    }
}
public class ThreadA extends Thread{

    private Service service;
    
    public ThreadA(Service service) {
        this.service = service;
    }
    
    @Override
    public void run() {
        service.printA();
    }
}
public class ThreadB extends Thread{

    private Service service;
    
    public ThreadB(Service service) {
        this.service = service;
    }
    
    @Override
    public void run() {
        service.printB();
    }
}
public class Test {
    public static void main(String[] args) {
        Service service = new Service();
        ThreadA threadA = new ThreadA(service);
        threadA.start();
        ThreadB threadB = new ThreadB(service);
        threadB.start();
    }
}
image.png

由于Service中的synchronized 锁住了整个对象,因此当printA锁未释放的情况下printB的方法一直处于等待状态,由此造成了死锁.

解决方案:使用同步代码块

public class Service {

    Object obj1 = new Object();
    public void printA() {
        synchronized (obj1) {
            System.out.println("printA begain");
            while (true) {
            }
        }
    }
    
    Object obj2 = new Object();
    public void printB() {
        synchronized (obj2) {
            System.out.println("printB begain");
            System.out.println("printB end");
        }
    }
}
image.png

使用同步代码块修改后,对象锁则锁住的是Service的成员变量,由于两者锁住的对象各部相同,因此不会造成线程死锁

相关文章

网友评论

      本文标题:同步synchronized方法无限等待与解决

      本文链接:https://www.haomeiwen.com/subject/wejfbqtx.html