//在这里实现接口(或者集成Thread)
public class Test implements Runnable{
private int i = 0;
static Object obj1 = new Object();// 线程锁的第一个‘锁’对象
static Object obj2 = new Object();// 线程锁的第二个‘锁’对象
public Test () {};// 重写构造方法
public Test (int i) {
this.i = i;
}
@Override
public void run() {
if (i == 1) {
// 锁住了对象obj1
synchronized (obj1) {
System.out.println(1);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
// 这里拿不到obj2因为第二个线程没有释放obj2
synchronized (obj2) {
System.out.println(11);
}
}
}else if(i==2) {
// 锁住了obj2
synchronized (obj2) {
System.out.println(2);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
// 这里拿不到obj1,因为线程1没有释放obj1
synchronized (obj1) {
System.out.println(22);
}
}
}
}
public static void main(String[] args) throws Exception {
Test test = new Test(1);
// 启动第一个线程
new Thread(test).start();
Test test2 = new Test(2);
// 启动第二个线程
new Thread(test2).start();
Thread.sleep(2000);
System.out.println("main线程执行");
}