多线程 synchronized 保证正确读写


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类型的参数.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值