国产化驱动经济自主性与科技创新的未来之路
579
2022-11-18
死锁的案例
当多线程处理共享数据时,就会涉及到线程安全问题,采用同步代码块或者同步方法,资源交错,操作不当会产生死锁问题!如下是一个死锁的案例,仅供参考
class BreadMilk implements Runnable { private String milk = "牛奶";// 保证有一份 private String bread = "面包"; boolean flag;// true,t1,执行,false,t2执行 @Override public void run() { if (flag) { // t1线程执行 synchronized (milk) { System.out.println(Thread.currentThread().getName() + ",已经拥有了" + milk); try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (bread) { System.out.println(Thread.currentThread().getName() + ",即拥有" + milk + ",又拥有" + bread); } } } else { // t2线程执行 synchronized (bread) { System.out.println(Thread.currentThread().getName() + ",已经拥有了" + bread); try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (milk) { System.out.println(Thread.currentThread().getName() + ",即拥有" + bread + ",又拥有" + milk); } } } }}public class DeadLock { public static void main(String[] args) { BreadMilk mt1 = new BreadMilk(); BreadMilk mt2 = new BreadMilk(); mt1.flag = true; mt2.flag = false; Thread t1 = new Thread(mt1, "张三"); Thread t2 = new Thread(mt2, "李四"); t1.start(); t2.start(); }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~