多线程控制类-AtomicInteger原子类解决非原子操作问题

1.demo代码:
package cn.yb.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子类解决非原子操作问题
 * @author yb
 *
 */
public class ThreadAutomicSlove {
//	static private int n;// 执行n++操作的变量
	static AtomicInteger auAtomicInteger;

	public static void main(String[] args) throws InterruptedException {
        int j = 0;
        while(j<100) {
//        	n=0;
        auAtomicInteger = new AtomicInteger(0);//创建原子整数,初始值是0
		Thread thread1 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 1000; i++) {
//					n++;
					auAtomicInteger.getAndIncrement();
				}
			}
		});
		Thread thread2 = new Thread(new Runnable() {

			public void run() {
				for (int i = 0; i < 1000; i++) {
//					n++;
					auAtomicInteger.getAndIncrement();
				}
			}
		});
		thread1.start();
		thread2.start();
		thread1.join();//线程1加入主线程
		thread2.join();//线程2加入主线程
		System.out.println("n的最终值是:"+auAtomicInteger.get());
		j++;
        }	
	}
}

2.运行效果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46266503/article/details/106985611