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);
}
}
来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/javaweb/140.html