java中的自增过程不是原子性操作

在Java多线程环境下,自增操作由于非原子性可能导致数据一致性问题。通过示例代码揭示了这个问题,表现为输出数据的不一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在java中多线程访问同一数据时,会出现数据不一致的问题。java中的自增操作需要多步完成,而且不是原子性操作控制。下面的代码说明了问题,源自java编程思想

</pre><pre code_snippet_id="1623662" snippet_file_name="blog_20160325_2_1202041" name="code" class="java">package synchonize;

public class EvenGenerator extends IntGenerator {
	private int currentEvenValue = 0;
	public int next(){
		++currentEvenValue;
		Thread.yield();
		++currentEvenValue;
		return currentEvenValue;
	}
	public static void main(String []args){
		EvenChecker.test(new EvenGenerator());
	}
	

}


package synchonize;

public abstract class IntGenerator {
	private volatile boolean canceled = false;
	public abstract int next();
	public void cancel(){
		canceled = true;
	}
	public boolean isCanceled(){
		return canceled;
	}

}

package synchonize;



import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EvenChecker implements Runnable{
	private IntGenerator generator;
	private final int id;
	public EvenChecker(IntGenerator g, int id){
		
		this.generator = g; 
		this.id = id;
	}
	public void run() {
		// TODO Auto-generated method stub
		while(!generator.isCanceled()){
			int val = generator.next();
			if(val %2 !=0){
				System.out.println(val + "not even!");
				generator.cancel();
			}
		}
	}
	public static void test(IntGenerator gp, int count){
		System.out.println("press control-c to exit");
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i=0; i < count; i++){
			exec.execute(new EvenChecker(gp, i));
			
		}exec.shutdown();
	}
	public static void test(IntGenerator gp){
		test(gp, 10);
	}
}

好不容易调出这个结果来

press control-c to exit
5not even!
3not even!
7not even!
3not even!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值