简单实现一个死锁
class A{}
class B{}
public class Demo {
static A a = new A();
static B b = new B();
public static void main(String[] args) {
new Thread(){
@Override
public void run() {
synchronized (a){
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b){
System.out.println(" has get b");
}
}
}
}.start();
new Thread(){
@Override
public void run() {
synchronized (b){
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a){
System.out.println(" has get a");
}
}
}
}.start();
}
}
另外一个写法:
public class MyDemo {
static A a = new A();
static B b = new B();
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
synchronized (a) {
try { Thread.sleep(2 * 1000); }
catch (InterruptedException e) { e.printStackTrace(); }
synchronized (b){
System.out.println("has get b");
}
}
}).start();
Thread.sleep(1 * 1000);
new Thread(()->{
synchronized (b) {
synchronized (a){
System.out.println("has get a");
}
}
}).start();
}
}
end
文章展示了两种在Java中创建死锁的简单方法。第一种是两个线程分别持有不同对象的锁并尝试获取对方持有的锁,导致双方等待。第二种是在主线程先启动一个线程获取一个锁,然后另一个线程尝试获取两个锁的顺序不同,同样造成死锁。这些例子用于说明线程同步的重要性。
683





