首页 > 代码库 > java synchronized(syncObject) 和 synchronized(this)

java synchronized(syncObject) 和 synchronized(this)

用synchronized(syncObject)看起来比较好如下:

public class test_sync extends Thread {

Integer x = 0;

public test_sync() {

}

public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
set_x(10);
}

public void set_x(int a) {
x = a;
synchronized (x) {
x.notify();
}
System.out.println("set_x " + x);
}

public int get_x() {
synchronized (x) {
try {
x.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return x;
}

public static void main(String[] args) {
test_sync t = new test_sync();
t.start();
System.out.println("get_x " + t.get_x());
}
}

但是这段代码不能工作!

修改如下:

public class test_sync extends Thread {

Integer x = 0;

public test_sync() {

}

public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
set_x(10);
}

public void set_x(int a) {
x = a;
synchronized (this) {
notify();
}
System.out.println("set_x " + x);
}

public int get_x() {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return x;
}

public static void main(String[] args) {
test_sync t = new test_sync();
t.start();
System.out.println("get_x " + t.get_x());
}
}

把synchronized (x)  改为synchronized (this); 

把x.notyfy()  改为notyfy(); 

把x.wait()  改为wait(); 

 就能工作,里面的差异是什么:

 

java synchronized(syncObject) 和 synchronized(this)