public class Test_1死锁 {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
//th1
Thread th1 = new Thread() {
@Override
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
synchronized (obj1) {
System.out.println("th1" + name + "hello");
synchronized (obj2) {
System.out.println("th1" + name + "world");
}
}
}
}
};
//th2
Thread th2 = new Thread() {
@Override
public void run() {
String name = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
synchronized (obj2) {
System.out.println("th2" + name + "你好");
synchronized (obj1) {
System.out.println("th2" + name + "中国");
}
}
}
}
};
th1.start();
th2.start();
}
}
死锁 :就是俩个线程t1和t2,t1拿着t2需要等待的锁不释放,而t2又拿着t1需要等待的锁不释放,俩个线程就这样一直僵持下去。
最新推荐文章于 2024-06-17 13:56:54 发布