多线程下的不可变对象模式

mac2024-01-30  34

1,针对共享资源而言,多线程访问,存在线程安全性问题。

2,除了使用synchronized关键字对共享资源上锁外,还可以在线程之前不共享资源状态。

3,代码示例如下

package com.wayne.unchangeable; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; public final class IntegerAccumulatorUnchange { private final int init; //构造器传入初始值 public IntegerAccumulatorUnchange(int init){ this.init = init; } public IntegerAccumulatorUnchange(IntegerAccumulatorUnchange a,int init){ System.out.println(a); this.init = a.getValue()+init; } //加法 public IntegerAccumulatorUnchange add(int i){ return new IntegerAccumulatorUnchange(this,i); } //返回当前值 public int getValue(){ return this.init; } public static void main(String[] args){ IntegerAccumulatorUnchange integerAccumulatorChange = new IntegerAccumulatorUnchange(0); IntStream.range(0,3).forEach(i-> new Thread(()->{ int inc = 0; while (true){ System.out.println(Thread.currentThread().getName()); int oldValue = integerAccumulatorChange.getValue(); int result = integerAccumulatorChange.add(inc).getValue(); System.out.println(oldValue+"+"+inc+"="+result); if(inc+ oldValue != result){ System.out.println("ERROR:"+oldValue+"+"+inc+"="+ result); } inc++; slowly(); } }).start()); } private static void slowly() { try{ TimeUnit.MILLISECONDS.sleep(1); }catch (InterruptedException e){ e.printStackTrace(); } } }

 

最新回复(0)