日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java多线程技术-Volatile关键字解析

發布時間:2024/9/5 java 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java多线程技术-Volatile关键字解析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

分析volatile關鍵字可以從這三個方面分析,什么是程序的原子性,什么是程序的可見性,什么是程序的有序性

什么是程序的原子性

以下語句那些是原子操作?

public class ThreadCounter implements Runnable {private int count = 0;@Overridepublic void run() {++count; // count++; }public static void main(String[] args) throws InterruptedException {ThreadCounter thread = new ThreadCounter();for(int i = 0; i< 10000; i++){new Thread(thread).start();}Thread.sleep(1000);//確保線程執行完 System.out.println(thread.count);} } View Code

演示結果:語句一和二是非原子操作,語句三和四是原子操作?

執行指令:javap -s -c ThreadCounter run方法的指令碼(count++): count++這行代碼分成了4個指令來執行,在多線程的情況下會不一致。

?解決方法:

public class ThreadCounter implements Runnable {private int count = 0;@Overridepublic void run() {synchronized (this) {++count;// count++; }}public static void main(String[] args) throws InterruptedException {ThreadCounter thread = new ThreadCounter();for(int i = 0; i< 10000; i++){new Thread(thread).start();}Thread.sleep(1000);//確保線程執行完 System.out.println(thread.count);} } View Code

什么是程序的可見性?

?

public class VolatileExample {boolean v =false;private void write(){v =true;}private void read(){while(!v){}System.out.println("程序結束!");}public static void main(String[] args) throws InterruptedException {final VolatileExample example = new VolatileExample();Thread thread1 = new Thread(()->{example.read();});thread1.start();Thread.sleep(1000);Thread thread2 = new Thread(()->{example.write();});thread2.start();} } View Code 演示結果: 程序沒有結束,read方法中的v沒有因write方法的修改而退出循環! 解決方法:為變量v添加volatile關鍵字 public class VolatileExample {volatile boolean v =false;private void write(){v =true;}private void read(){while(!v){}System.out.println("程序結束!");}public static void main(String[] args) throws InterruptedException {final VolatileExample example = new VolatileExample();Thread thread1 = new Thread(()->{example.read();});thread1.start();Thread.sleep(1000);Thread thread2 = new Thread(()->{example.write();});thread2.start();} } View Code

什么是程序的有序性?

?

Volatile應用場景

1.?狀態標記量? public class ThreadTest {private volatile boolean isContinue = false;private class HandleThread extends Thread {@Overridepublic void run() {while (isContinue) {// do something }};} } View Code

2.?double check?

?

總結:

volatile在可見性和有序性可以起到作用,但是不能保證原子性,是一種弱同步。

synchronized可以保證原子性,可見性,一致性,是一種強同步。

?

轉載于:https://www.cnblogs.com/lostyears/p/8297130.html

總結

以上是生活随笔為你收集整理的Java多线程技术-Volatile关键字解析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。