public class Test{
final Object lockA = new Object();
final Object lockB = new Object();
public static void main(String[] args) {
Test demo = new Test();
demo.startLock();
}
public void startLock(){
ThreadA a= new ThreadA(lockA,lockB);
ThreadB b= new ThreadB(lockA,lockB);
//start threads
a.start();
b.start();
}
}
class ThreadA extends Thread{
private Object lockA = null;
private Object lockB = null;
public ThreadA(Object a, Object b){
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockA) {
System.out.println("*** Thead A: ***: Lock A" );
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println("*** Thead A: ***: Lock B" );
}
}
System.out.println("*** Thead A: ***: Finished" );
}
}
class ThreadB extends Thread{
private Object lockA = null;
private Object lockB = null;
public ThreadB(Object a, Object b){
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockB) {
System.out.println("*** Thead B: ***: Lock B" );
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockA) {
System.out.println("***** Thead B: *****: Lock A" );
}
}
System.out.println("***** Thead B: *****: Finished" );
}
}
这是一死锁线程? 怎样才能避免死锁的发生?
|