Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

「一入 Java 深似海 」第3期2节死锁有问题 #12

Open
purgeyao opened this issue Mar 18, 2019 · 2 comments
Open

「一入 Java 深似海 」第3期2节死锁有问题 #12

purgeyao opened this issue Mar 18, 2019 · 2 comments

Comments

@purgeyao
Copy link
Contributor

不加线程等待会出现一个线程执行完成,第二个线程才执行(偶尔出现)
在每个线程第一个对象获取锁之后加线程等待可以解决这个问题
public class ThreadDeadLock {

public static void main(String[] args) {

    Object o1 = new Object();

    Object o2 = new Object();

    Thread thread1 = new Thread(() -> {

        synchronized (o1){
            System.out.println(Thread.currentThread() + " get o1");
            // 线程等待
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o2){
                System.out.println(Thread.currentThread() + " get o2");
            }
        }
    });

    Thread thread2 = new Thread(() -> {

        synchronized (o2){
            System.out.println(Thread.currentThread() + " get o2");
            // 线程等待
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o1){
                System.out.println(Thread.currentThread() + " get o1");
            }
        }
    });

    thread1.start();
    thread2.start();
}

}

@mercyblitz
Copy link
Owner

欢迎提交 PR~

@myejb22
Copy link

myejb22 commented Mar 19, 2019

我的理解是:由于o1对象引用了o2对象,o2对象又引用了o1对象,并且o1与o2都加了同步锁,相互不释放,因此进入了死锁。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants