当前位置: 首页 > 后端技术 > Java

死锁简介

时间:2023-04-01 22:17:35 Java

死锁:两个或多个线程在执行过程中,由于争夺资源或相互等待,相互等待,线程不再执行。根据以上示例图构建链接的死锁程序(1)DeadLockpackagecom.high.concurrency.currency02.eat;publicclassDeadLockextendsThread{privateStringfirst;私有字符串第二;publicDeadLock(Stringname,Stringfirst,Stringsecond){super(name);this.first=第一;this.second=第二个;}@Overridepublicvoidrun(){synchronized(first){try{System.out.println(this.getName()+"...synchronized:===>【first】"+first);线程.睡眠(1000L);synchronized(second){System.out.println(this.getName()+"...synchronized:===>【second】"+second);}}catch(InterruptedExceptione){}}}publicstaticvoidmain(String[]args)throwsInterruptedException{StringlockA="lockA";StringlockB="lockB";死锁t1=newDeadLock("t1",lockA,lockB);死锁t2=新死锁k("t2",锁B,锁A);t1.开始();t2.开始();t1.join();t2.join();}}(2)PhilosopherEatingpackagecom.high.concurrency.currency02.eat;publicclassPhilosopherEatingextendsThread{protectedObjecttool;静态对象fork1=新对象();静态对象fork2=新对象();publicPhilosopherEating(Objectobj){this.tool=obj;if(tool==fork1){this.setName("哲学家A");}if(tool==fork2){this.setName("哲学家B");}}@Overridepublicvoidrun(){if(tool==fork1){synchronized(fork1){try{Thread.sleep(500);}catch(Exceptione){e.printStackTrace();}synchronized(fork2){System.out.println("哲学家A开始吃饭了");}}}如果(工具==fork2){同步(fork2){尝试{Thread.sleep(500);}catch(InterruptedExceptione){e.printStackTrace();}synchronized(fork1){System.out.println("哲学家B开始吃饭");}}}}publicstaticvoidmain(String[]args)throwsInterruptedException{PhilosopherEatingphilosonpherA=newPhilosopherEating(fork1);PhilosopherEatingphilosonpherB=newPhilosopherEating(fork2);philosonpherA.start();philosonpherB.start(););}}以上程序都体现了一个特点:有两个线程,我用当前资源去申请对方正在使用的资源,但是对方一直没有释放资源,导致线程阻塞。查找线程死锁的方法:jps+jstack首先在终端输入jps,找到对应的死锁进程号:得到对应的死锁进程,输入jstack+进程号,找到对应的错误信息,根据下面的修改错误信息