java - 多线程死锁测试
问题描述
package test;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.TimeUnit;/** * Created by rhwayfun on 16-4-3. */public class ThreadTest { private static DateFormat format = new SimpleDateFormat('HH:mm:ss'); public synchronized void tryOther(ThreadTest other) throws InterruptedException {System.out.println(Thread.currentThread().getName() + ' enter tryOther method at ' + format.format(new Date())); System.out.println(Thread.currentThread().getName() + ' tryOther method is about to invoke other method at ' + format.format(new Date()));other.other(); } public synchronized void other() throws InterruptedException {System.out.println(Thread.currentThread().getName() + ' enter other method atatatatat ' + format.format(new Date())); } public static void main(String[] args) throws InterruptedException {final ThreadTest d1 = new ThreadTest();final ThreadTest d2 = new ThreadTest();Thread t1 = new Thread(new Runnable() { public void run() {try { d1.tryOther(d2);} catch (InterruptedException e) { e.printStackTrace();} }}, 'threadA');Thread t2 = new Thread(new Runnable() { public void run() {try { d2.tryOther(d1);} catch (InterruptedException e) { e.printStackTrace();} }}, 'threadB');t1.start();//让threadA先运行一秒TimeUnit.SECONDS.sleep(1);t2.start(); }}
如上,随便找的产生死锁的代码,问题:TimeUnit.SECONDS.sleep(1);加上这行后,不存在死锁问题。sleep并不释放锁,为何这边死锁情况会消失。输出结果为:threadA enter tryOther method at 15:37:39threadA tryOther method is about to invoke other method at 15:37:39threadA enter other method atatatatat 15:37:39threadB enter tryOther method at 15:37:40threadB tryOther method is about to invoke other method at 15:37:40threadB enter other method atatatatat 15:37:40
注掉这行,正常死锁。输出结果为:threadB enter tryOther method at 15:37:10threadA enter tryOther method at 15:37:10threadB tryOther method is about to invoke other method at 15:37:10threadA tryOther method is about to invoke other method at 15:37:10
问题解答
回答1:线程A拿到tryOther锁但是他还要得到other的锁线程B拿到tryOther的锁但是他还要拿到other的锁 有可能A刚刚释放锁B也刚刚释放tryOther的锁.此时但是他们同时都想要获取other的锁 此时谁也不让谁 发生死锁解决方法让俩个线程不要同时去抢第二把锁.让A停一会但是如果你把时间调成纳秒级别 多次尝试也会发生死锁不建议这样预防死锁.如果并发量高的情况下.
回答2:双方在争同一把锁,不会死锁啊
回答3:自己突然知道为什么了,懒得删帖子了。写下我的看法,如果有错,欢迎指正,轻喷在没有sleep时,a线程启动,完成tryOther方法,释放锁并去执行other方法,此时b获得锁执行tryOther方法,此时a在other方法中所需资源被b线程锁住,b在执行完tryOther后需要获得a资源,由此产生死锁。
加上sleep后。在a执行tryOther方法释放锁,此时b线程并没有执行,此时顺利获得other锁。2s后b线程执行,无死锁环境。
相关文章:
1. PHP能实现百度网盘的自动化么?2. node.js - 微信的自动回复问题3. android - 使用vue.js进行原生开发如何进行Class绑定4. 网页爬虫 - python requests爬虫,如何post payload5. css3 - 请问一下在移动端CSS布局布局中通常需要用到哪些元素,属性?6. javascript - 百度图片切换图片时url会改变,但无刷新,没用hash,IE8也支持,请问是用了什么技术?7. MySQL 水平拆分之后,自动增长的ID有什么好的解决办法?8. mysql如何添加索引的时候指定索引方式9. angular.js - 各位大神们,你们混合开发,web方式中更推荐用什么框架呀? react?vue?angular?谢谢~10. 我正在使用jsp / jstl / spring动态生成css和js。如何将此结果放置在头部的链接标签中。不在头部的脚本标签中
