码迷,mamicode.com
首页 > 编程语言 > 详细

线程中死锁的demo

时间:2018-03-18 14:53:46      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:print   pre   adl   this   stat   public   art   pos   []   

/*
虽然同步的出现解决了线程安全问题。
但是也带来了一些弊端:
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

标签:print   pre   adl   this   stat   public   art   pos   []   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!