线程:volatile关键字
生活随笔
收集整理的這篇文章主要介紹了
线程:volatile关键字
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? 關(guān)鍵字volatile的作用是強(qiáng)制從公共堆棧中取得變量的值,而不是從線程私有數(shù)據(jù)棧中取得變量的值。
? 使用volatile關(guān)鍵字增加了實(shí)例變量在多個(gè)線程之間的可見性。但volatile關(guān)鍵字最致命的缺點(diǎn)是不支持原子性。
? volatile解決的是變量在多個(gè)線程之間的可見性,而synchronized關(guān)鍵字解決的是多個(gè)線程之間訪問資源的同步性。
?
使用原子類進(jìn)行i++操作
import java.util.concurrent.atomic.AtomicInteger;public class AtomicIntegerThread extends Thread{// 原子類private AtomicInteger count = new AtomicInteger(0);@Overridepublic void run(){for(int i=0; i<10000; i++){System.out.println(count.incrementAndGet());}} }public class Run {public static void main(String[] args){AtomicIntegerThread countService = new AtomicIntegerThread();Thread t1 = new Thread(countService);t1.start();Thread t2 = new Thread(countService);t2.start();Thread t3 = new Thread(countService);t3.start();Thread t4 = new Thread(countService);t4.start();Thread t5 = new Thread(countService);t5.start();} }?
總結(jié)
以上是生活随笔為你收集整理的线程:volatile关键字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程:synchronized
- 下一篇: 线程:等待/通知机制