多线程中volatile使用的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29807745/article/details/75287091
package com.casking.cdds.modules.test.web;

public class Counter {

	//volatile关键字能保证多个内存块中的引用值是最新的可见性,不能保证原子性。可见性只能保证每次读取的是最新的值,但是volatile没办法保证对变量的操作的原子性。
	public volatile static int count = 0;

	public synchronized static void inc() {

		// 这里延迟1秒,使得结果明显
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
		}
		count++;

	}

	public static void main(String[] args) {

		// 同时启动1000个线程,去进行i++计算,看看实际结果
		for (int i = 0; i < 1000; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Counter.inc();
				}
			}).start();
		}

		// 方法返回活动线程的当前线程的线程组中的数量---主线程下
		while (Thread.activeCount() > 1) // 保证前面的线程都执行完
			Thread.yield(); //当一个线程使用了这个方法之后,它就会把自己CPU执行的时间让掉,让自己或者其它的线程运行。
		// 这里每次运行的值都有可能不同,可能为1000
		System.out.println("运行结果:Counter.count=" + Counter.count);
	}
}


猜你喜欢

转载自blog.csdn.net/qq_29807745/article/details/75287091