首页 > 代码库 > java学习笔记 死锁
java学习笔记 死锁
在锁对象期间,会产生一个问题就是死锁,双方都在等在对方释放资源
范例:
public class Test { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); MyThread mt2 = new MyThread(); mt1.flag = 1; mt2.flag = 2; Thread t1 = new Thread(mt1); Thread t2 = new Thread(mt2); t1.start(); t2.start(); }}class MyThread implements Runnable { static Object ob1 = new Object();//注意是static static Object ob2 = new Object();//注意是static int flag = 0; public void run() { if (flag == 1) { System.out.println("flag = 1"); synchronized (ob1) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("休眠中断"); } synchronized (ob2) { System.out.println("1"); } } } if (flag == 2) { System.out.println("flag = 2"); synchronized (ob2) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("休眠中断"); } synchronized (ob1) { System.out.println("2"); } } } }}
java学习笔记 死锁
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。