class SerialNumberGenerator{
private static volatile int i=0;
//不是同步的,多个线程操作可能会冲突
public static int nextSerialNumber(){
return i++;
}
}
class CircularSet{
private int[] array;
private int len;
private int index=0;
public CircularSet(int size){
this.len=size;
array=new int[len];
for(int i=0;i<len;i++){
array[i]=-1;
}
}
public synchronized void add(int n){
array[index]=n;
index=++index%len;
}
public synchronized boolean contains(int n){
for(int i=0;i<len;i++){
if(array[i]==n){
return true;
}
}
return false;
}
}
public class Test {
private static final int SIZE=100;
private static CircularSet mCircularSet=new CircularSet(1000);
private static ExecutorService mExecutorService=Executors.newCachedThreadPool();
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<SIZE;i++){
mExecutorService.execute(new SerialChecker());
}
TimeUnit.SECONDS.sleep(5);
}
static class SerialChecker implements Runnable{
@Override
public void run() {
while(true){
int serial=SerialNumberGenerator.nextSerialNumber();
if(mCircularSet.contains(serial)){
System.out.println("Duplicate:"+serial);
System.exit(0);
}
mCircularSet.add(serial);
}
}
}
}
java中证明++操作是非原子的
最新推荐文章于 2023-03-14 23:41:51 发布