你这 step1 step2 是两个对象,没有任何共享的东西,你想同步什么呢?不要说是 share 方法,那可不是这样同的。
synchronized 修饰的方法是在不同方法同时调用时会同步。
----------------------------------------
class A {
synchronized void read () throws InterruptedException {
System.out.println(Thread.currentThread().getId() + " Reading...");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId() + " Reading done.");
}
}
public class Demo {
public static void main (String args[]) {
final A a = new A();
Thread t1 = new Thread() {
public void run () {
try {
a.read();
} catch (InterruptedException ie) {}
}
};
Thread t2 = new Thread() {
public void run () {
try {
a.read();
} catch (InterruptedException ie) {}
}
};
t1.start();
t2.start();
}
}
-----------------------------运行结果----------------------------------
8 Reading...
8 Reading done.
9 Reading...
9 Reading done.
每个线程都调用 a.read(); 两个线程几乎是同时 start 的。但是 9 必须会等 8 结束。这才是一个正确的同步例子。
你想要什么结果?