不可变对象设计模式

        共享的资源,是指在多个线程同时对其访问的情况下,各个线程都会使其发生变化,线程安全的目的是在受控的并发访问中防止数据发生变化。除了使用synchronized关键字同步对资源的写操作之外,还可以在线程间不共享资源状态,甚至将资源的状态设置为不可变。不可变最核心的地方在于不给外部修改共享资源的机会。 

示例代码如下:

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public final class IntegerAccumulator {
private final int init;

public IntegerAccumulator(int init) {
this.init=init;
}

public IntegerAccumulator(IntegerAccumulator accumulator, int init) {
this.init=accumulator.getValue()+init;
}

public IntegerAccumulator add(int i) {
return new IntegerAccumulator(this,i);
}

public int getValue() {
return this.init;
}

private static void slowly() {
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
IntegerAccumulator accumulator=new IntegerAccumulator(0);
IntStream.range(0, 3).forEach(i->new Thread(()->{
int inc=0;
while(true) {
int oldValue=accumulator.getValue();
int result=accumulator.add(inc).getValue();
System.out.println(oldValue+"+"+inc+"="+result);
if(inc+oldValue!=result) {
System.err.println("Error:"+oldValue+"+"+inc+"="+result);
}
inc++;
slowly();
}
}).start());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值