首页 > 编程语言 > 详细

java synchronized(syncObject) 和 synchronized(this)

时间:2014-10-23 09:14:41      阅读:264      评论:0      收藏:0      [点我收藏+]

用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)

原文:http://www.cnblogs.com/lion382/p/4044861.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!