线程 6. 死锁

没有办法解决,只能避免

  • java同步机制解决了线程安全问题,但是同时也引发了死锁现象。
    • 死锁现象如何解决呢: 没法解决。 只能尽量的避免死锁现象。
    • 死锁现象出现 的根本原因:
      1. 存在两个或者两个以上的线程存在。
      2. 多个线程必须共享两个或者两个以上的资源。
class DeadLockThread extends Thread{
    public DeadLockThread(String name){
        super(name);
    }
    @Override
    public void run() {
        if("张三".equals(this.getName())){
            synchronized ("遥控器") {
                System.out.println(this.getName()+"取走了遥控器,准备取电池");
                synchronized ("电池") {
                    System.out.println(this.getName()+"取到了电池,开着空调爽歪歪的吹着 !!");
                }
            }
        }else if("李四".equals(this.getName())){
            synchronized ("电池") {
                System.out.println(this.getName()+"取走了电池,准备取取遥控器");
                synchronized ("遥控器") {
                    System.out.println(this.getName()+"取走了遥控器,开着空调爽歪歪的吹着 !!");
                }
            }
        }
    }
}
public class Demo2 {
    public static void main(String[] args) {
        //创建了线程对象
        DeadLockThread thread1 = new DeadLockThread("张三");
        DeadLockThread thread2 = new DeadLockThread("李四");
        thread1.setPriority(10);
        thread2.setPriority(1);
        //调用start方法启动线程
        thread1.start();
        thread2.start();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容