简单实现一个死锁
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