java 多线程-死锁的产生以及解决方案
死锁:
过多的同步造成相互不释放资源,从而过多地等待,一般发生于
同步中持有多个对象的锁
snchronized锁住对象同时,另一个snchronized就不能锁该对象
避免在一个代码块中,同时持有多个对象的锁
死锁:
public class tt {public static void main(String[]args){ markup m1=new markup(1,"me"); markup m2 =new markup(2,"she"); m1.start(); m2.start();}}//口红class lipstick{}//镜子class mirror{}//化妆class markup extends Thread{//加静态表示一份,不管创建几个对象都是一份static lipstick lip=new lipstick();static mirror mir=new mirror();//选择int choice;String girl;public markup(int choice,String girl){ this.choice=choice; this.girl=girl;}public void run(){ mark();}//相互持有对方的对象锁-->可能造成死锁//加等待时间是为了让另一个线程锁相同对象的时候,该线程//锁的相同对象还没有结束//在这个死锁中,第一个线程内的mir要等第二个已经开始的mir锁结束才能执行//而第二个线程内的mir结束需要等第一个线程内的lip解锁才行private void mark(){ if(choice==0) { synchronized(lip) { System.out.println(this.girl+"获得口红"); //一秒后想要镜子 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(mir) { System.out.println(this.girl+"获得镜子"); } } }else { synchronized(mir) { System.out.println(this.girl+"获得镜子"); //2秒后想要口红 try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(lip) { System.out.println(this.girl+"获得口红"); } } }}}
解决:
public class tt {public static void main(String[]args){ markup m1=new markup(1,"me"); markup m2 =new markup(2,"she"); m1.start(); m2.start();}}//口红class lipstick{}//镜子class mirror{}//化妆class markup extends Thread{//加静态表示一份,不管创建几个对象都是一份static lipstick lip=new lipstick();static mirror mir=new mirror();//选择int choice;String girl;public markup(int choice,String girl){ this.choice=choice; this.girl=girl;}public void run(){ mark();}{ if(choice==0) { synchronized(lip) { System.out.println(this.girl+"获得口红"); //一秒后想要镜子 try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized(mir) { System.out.println(this.girl+"获得镜子"); } }else { synchronized(mir) { System.out.println(this.girl+"获得镜子"); //2秒后想要口红 try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized(lip) { System.out.println(this.girl+"获得口红"); } }}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。