运行以下代码
[java]
public class Test_Thread4 extends Thread {
public final Object lock = new Object();//注意lock应该被final修饰,为保证Object Reference在整个系统运行过程中都保持不变
public Test_Thread4(String name) {
super(name);
}
public static void main(String[] args) {
Test_Thread4 t = new Test_Thread4("one");
Test_Thread4 t2 = new Test_Thread4("two");
t.start();
try {
Thread.sleep(2000);
t2.start();
t.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The main Thread over");
}
public void run() {
System.out.println(this.getName() + " start");
synchronized (lock) {
try {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName());
Thread.sleep(300);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
}
System.out.println(this.getName() + " has over");
}
}
运行结果:
one start
one
one
one
one
one
one
one
two start
two
one
two
one
two
one
two
one has over
two
two
two
two
two
two
two has over
The main Thread over
从 one
two start
two
one
two
one
two
one
two 端似乎可以看出同步失败,后来发现是锁的问题,目前锁是实例变量,每个线程就存在一个独立的锁,所以结果不能同步,做以下修改:
[java]
public static final Object lock = new Object();//即可
摘自 wugui414的专栏