标签:死锁
什么是死锁?
简单理解就是两个线程互相持有两个锁,都在等待对方释放锁而去获取对方的锁继续执行下面的代码,就这样无线死等下去,就卡住了。
实现一个死锁,代码如下:
public class Sisuo { public static void main(String[] args) { A a1 = new A(true); A a2 = new A(false); Thread t1 = new Thread(a1); Thread t2 = new Thread(a2); t1.start(); t2.start(); } } class A implements Runnable { private boolean flag; A(boolean flag){ this.flag = flag; } @Override public void run() { if(flag) { synchronized(MyLock.lock1) { System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); synchronized(MyLock.lock2) { System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); } } } else { synchronized(MyLock.lock2) { System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbb"); synchronized(MyLock.lock1) { System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } } } } } class MyLock{ MyLock() { } public static final MyLock lock1 = new MyLock(); public static final MyLock lock2 = new MyLock(); }
本文出自 “12212886” 博客,请务必保留此出处http://12222886.blog.51cto.com/12212886/1963413
标签:死锁
原文地址:http://12222886.blog.51cto.com/12212886/1963413