多线程控制类-多线程下非原子操作的问题演示

1.demo代码:
package cn.yb.thread;
/**
 * 多线程下非原子操作的问题
 * @author yb
 *
 */
public class ThreadAutomicDemo {
	static private int n;// 执行n++操作的变量

	public static void main(String[] args) throws InterruptedException {
        int j = 0;
        while(j<100) {
		n = 0;
		Thread thread1 = new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 1000; i++) {
					n++;
				}
			}
		});
		Thread thread2 = new Thread(new Runnable() {

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

2.运行效果:

在这里插入图片描述

猜你喜欢

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