什么是死锁?
简单理解就是两个线程互相持有两个锁,都在等待对方释放锁而去获取对方的锁继续执行下面的代码,就这样无线死等下去,就卡住了。
实现一个死锁,代码如下:
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(); }
时间: 2024-10-12 07:28:33