并发环境下,不安全发布对象示例代码

package com.mm.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestConcurrent {
	public static void main(String[] args) throws InterruptedException {
		final List<ValueOwner> list = new ArrayList<>(10000);
		for(int i = 0; i < 10000; i++){
			list.add(new ValueOwner());
		}
		
		CountDownLatch latch = new CountDownLatch(1);
		
		CountDownLatch watchDog = new CountDownLatch(200);
		
		ExecutorService es = Executors.newFixedThreadPool(200);
		for(int i = 0; i < 200; i++){
			es.execute(new Runnable() {
				
				@Override
				public void run() {
					try {
						latch.await();
						for(ValueOwner vo : list){
							vo.check();
						}
						watchDog.countDown();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		latch.countDown();
		int n = 0;
		for(ValueOwner vo : list){
			vo.setValue(++n);
		}
		
		watchDog.await();
		es.shutdown();
	}
}

class ValueOwner {
	private int value;

	public ValueOwner() {
	}

	public void setValue(int value) {
		this.value = value;
	}

	public void check() {
		if (value != value) {
			throw new RuntimeException();
		}
	}
}

分析: 调用check的线程取第一个value的时候看到的时 对象初始化的属性值value=0,在读第二个的时候读到的是主线程set的value值  发现两个不一致 抛出异常。java

相关文章
相关标签/搜索