package scjp;
public class Demo712 implements Runnable{
private int a;
private int b;
public int read() {
return a+b;
}
public void set(int a,int b){
this.a=a;
this.b=b;
}
@Override
public void run() {
for(int i=0;i<10;i++){
this.set(i, i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i + " " + this.read());
}
}
public static void main(String[] args) {
Demo712 demo712=new Demo712();
Thread t1=new Thread(demo712);
Thread t2=new Thread(demo712);
t1.start();
t2.start();
}
}
输出为:
0 0
0 2
1 2
1 4
2 4
2 6
3 6
3 8
4 8
4 10
5 10
5 12
6 12
6 14
7 14
7 16
8 16
8 18
9 18
9 18
其中
1 4
2 6
显然为不同步。如何给它们加上同步:
A.在方法read和set上都加 synchronized
public synchronized int read() {
return a+b;
}
public synchronized void set(int a,int b){
this.a=a;
this.b=b;
}B.给块加上synchronized
public int read() {
synchronized(this){
return a+b;
}
}
public synchronized void set(int a,int b){
synchronized(this){
this.a=a;
this.b=b;
}
}这两种做法都是可以的,输出结果我就不列了.下面讨论错误的情况:
public int read() {
synchronized(a){
return a+b;
}
}
public synchronized void set(int a,int b){
synchronized(b){
this.a=a;
this.b=b;
}
}这段代码有两个问题,第一synchronized的格式是这样的
synchronized(object){
//synchronized block
}
a,b是int型变量,int是primitive(int byte char boolean short long double float),它不是对象,所以编译会报错.要让这段编译通过得把a,b申明为Integer或者其它Object的类型.
第二,同步的变量只有a,需要a,b全部同步输出才正确,修正这个问题只有用前面的两种办法了,因为正如前面看到的synchronized也只能接受一个Object类型的参数.

被折叠的 条评论
为什么被折叠?



