首页 > 编程语言 > 详细

线程中死锁的demo

时间:2018-03-18 14:45:40      阅读:228      评论:0      收藏:0      [点我收藏+]

/*
虽然同步的出现解决了线程安全问题。
但是也带来了一些弊端:
1,效率会降低。
2,容易引发死锁。

死锁经常出现的状况为:同步嵌套。


*/



class Test implements Runnable { private boolean flag; Test(boolean flag) { this.flag = flag; } public void run() { if(flag) { while(true) { synchronized(MyLock.locka) { System.out.println(Thread.currentThread().getName()+"...if......locka"); synchronized(MyLock.lockb) { System.out.println(Thread.currentThread().getName()+"...if......lockb"); } } } } else { while(true) { synchronized(MyLock.lockb) { System.out.println(Thread.currentThread().getName()+"...else..........lockb"); synchronized(MyLock.locka) { System.out.println(Thread.currentThread().getName()+"...else..........locka"); } } } } } } class MyLock { public static Object locka = new Object(); public static Object lockb = new Object(); } class DeadLockTest { public static void main(String[] args) { Test t1 = new Test(true); Test t2 = new Test(false); Thread th1 = new Thread(t1,"С?"); Thread th2 = new Thread(t2,"κ?"); th1.start(); th2.start(); } }

  

线程中死锁的demo

原文:https://www.cnblogs.com/liushisaonian/p/8595264.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!