0
点赞
收藏
分享

微信扫一扫

多线程引发的死锁问题

王老师说 2022-04-13 阅读 57
java
package com.xt.java;

import static java.lang.Thread.sleep;

/**
 * 演示线程的死锁问题
 * 1、死锁的理解:不同的进程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
 * 2、说明:
 *    1)出现死锁后,不会报错,不会出现异常,不会有提示,只是所有线程都出于阻塞状态,无法继续。
 *    2)我们使用同步时,要避免出现死锁
 * @author tyl
 * @creat 2022-04-10-19:30
 */
public class ThreadTest {
    public static void main(String[] args) {
        StringBuffer s1=new StringBuffer();
        StringBuffer s2=new StringBuffer();

        new Thread(){
            @Override
            public void run() {
                synchronized (s1){
                    s1.append('a');
                    s2.append('1');
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s2){
                        s1.append('b');
                        s2.append('2');
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){
                    s1.append('c');
                    s2.append('3');
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s1){
                        s1.append('d');
                        s2.append('4');
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}

举报

相关推荐

0 条评论