第一种卡住:
public class Join {
public static void main(String[] args) {
Object oo = new Object();
MyThread thread1 = new MyThread("thread1 -- ");
// oo = thread1;
thread1.setOo(oo);
thread1.start();
synchronized (oo) {
for (int i = 0; i < 20; i++) {
if (i == 10) {
try {
oo.wait(0);
thread1.join();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " -- " + i);
}
}
}
}
class MyThread extends Thread {
private String name;
private Object oo;
public void setOo(Object oo) {
this.oo = oo;
}
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 50; i++) {
System.out.println(name + i);
}
}
}
}
第二种卡住:
public class Join {
public static void main(String[] args) {
Object oo = new Object();
MyThread thread1 = new MyThread("thread1 -- ");
// oo = thread1;
thread1.setOo(oo);
thread1.start();
synchronized (oo) {
for (int i = 0; i < 20; i++) {
if (i == 10) {
try {
oo.wait(0);
thread1.join();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " -- " + i);
}
}
}
}
class MyThread extends Thread {
private String name;
private Object oo;
public void setOo(Object oo) {
this.oo = oo;
}
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
synchronized (oo) {
for (int i = 0; i < 50; i++) {
System.out.println(name + i);
}
}
}
}
结论:mythread类中不论锁是oo还是this都会卡住,为什么呢?