Java中死锁问题
package Text;
public class DeadLock {
// 死锁概念
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
// 初始化线程对象
Thread thread1 = new Thread1(o1,o2);
Thread thread2 = new Thread2(o1,o2);
// 启动线程
thread1.start();
thread2.start();
}
}
// 线程1
class Thread1 extends Thread{
Object o1;
Object o2;
public Thread1(Object o1,Object o2) {
this.o1 = o1;
this.o2 = o2;
}
//当Thread1锁了o1等待o2时,此时o2已经被Thread2锁了,故发生死锁现象
public void run() {
synchronized (o1){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
}
}
}
}
// 线程2
class Thread2 extends Thread{
Object o1;
Object o2;
public Thread2(Object o1,Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized (o2){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
}
}
}
}