Java多線程常用的幾個關鍵字
二、volatile
作用:volatile關鍵字的作用是:使變量在多個線程間可見(具有可見性),但是僅靠volatile是不能保證線程的安全性,volatile關鍵字不具備synchronized關鍵字的原子性。
Demo1:
package com.ietree.multithread.sync;
public class RunThread extends Thread {
// volatile
private boolean isRunning = true;
private void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public void run() {
System.out.println("進入run方法..");
int i = 0;
while (isRunning == true) {
// ..
}
System.out.println("線程停止");
}
public static void main(String[] args) throws InterruptedException {
RunThread rt = new RunThread();
rt.start();
Thread.sleep(1000);
rt.setRunning(false);
System.out.println("isRunning的值已經被設置了false");
}
}
程序輸出:
進入run方法..
isRunning的值已經被設置了false
之后進入死循環
Demo2:
package com.ietree.multithread.sync;
public class RunThread extends Thread {
// volatile
private volatile boolean isRunning = true;
private void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
public void run() {
System.out.println("進入run方法..");
int i = 0;
while (isRunning == true) {
// ..
}
System.out.println("線程停止");
}
public static void main(String[] args) throws InterruptedException {
RunThread rt = new RunThread();
rt.start();
Thread.sleep(1000);
rt.setRunning(false);
System.out.println("isRunning的值已經被設置了false");
}
}
程序輸出:
isRunning的值已經被設置了false
線程停止
總結:當多個線程之間需要根據某個條件確定 哪個線程可以執行時,要確保這個條件在 線程之間是可見的。因此,可以用volatile修飾。
volatile 與 synchronized 的比較:
①volatile輕量級,只能修飾變量。synchronized重量級,還可修飾方法
②volatile只能保證數據的可見性,不能用來同步,因為多個線程并發訪問volatile修飾的變量不會阻塞。
synchronized不僅保證可見性,而且還保證原子性,因為,只有獲得了鎖的線程才能進入臨界區,從而保證臨界區中的所有語句都全部執行。多個線程爭搶synchronized鎖對象時,會出現阻塞。
線程安全性包括兩個方面,①可見性。②原子性。
從上面自增的例子中可以看出:僅僅使用volatile并不能保證線程安全性。而synchronized則可實現線程的安全性。
【Java多線程常用的幾個關鍵字】相關文章: