共享的资源,是指在多个线程同时对其访问的情况下,各个线程都会使其发生变化,线程安全的目的是在受控的并发访问中防止数据发生变化。除了使用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());}}