線程A
public class ThreadA implements Runnable {
private A a;
private B b;
public ThreadA(A a, B b) {
super();
this.a = a;
this.b = b;
}
@Override
public void run() {
System.out.println("A線程啓動");
synchronized (a) {
System.out.println("A線程持有a對象");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (b) {
System.out.println("A線程持有b對象");
}
}
System.out.println("A線程結束");
}
}
線程B
public class ThreadB extends Thread {
private A a;
private B b;
public ThreadB(A a, B b) {
super();
this.a = a;
this.b = b;
}
@Override
public void run() {
System.out.println("B線程啓動");
synchronized (b) {
System.out.println("B線程持有b對象");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (a) {
System.out.println("B線程持有a對象");
}
}
System.out.println("B線程結束");
}
}
對象A,B
public class A {
}
public class B {
}
測試
public class Test {
public static void main(String[] args) {
A a = new A();
B b = new B();
ThreadA ta = new ThreadA(a, b);
new Thread(ta).start();
ThreadB tb = new ThreadB(a,b);
tb.start();
}
}