线程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();
}
}