volatile關(guān)鍵字增加了實例變量在多個線程之間的可見性,但是不具備原子性。
package com.wkcto.volatilekw;
/**
* volatile不是具備原子性
* Author: 老崔
*/
public class Test03 {
public static void main(String[] args) {
//在main線程中創(chuàng)建10個子線程
for (int i = 0; i < 100; i++) {
new MyThread().start();
}
}
static class MyThread extends Thread{
//volatile關(guān)鍵僅僅是表示所有線程從主內(nèi)存讀取count變量的值
public static int count;
/* //這段代碼運行后不是線程安全的,想要線程安全,需要使用synchronized進行同步,如果使用synchronized同時,也就不需要volatile關(guān)鍵了
public static void addCount(){
for (int i = 0; i < 1000; i++) {
//count++不是原子操作
count++;
}
System.out.println(Thread.currentThread().getName() + " count=" + count);
}*/
public synchronized static void addCount(){
for (int i = 0; i < 1000; i++) {
//count++不是原子操作
count++;
}
System.out.println(Thread.currentThread().getName() + " count=" + count);
}
@Override
public void run() {
addCount();
}
}
}