天天看點

JAVA多線程的變量共享

//非同步共享變量
public class Novisibility{
  private static boolean ready;
  private static int number;

  //建立線程,當ready值為true的時候,輸出number值
  private static class ReaderThread extends Thread{
    public void run(){
      while(!ready){
        Thread.yield();
      }
      System.out.println(number);
    }
  }
 
  public static void main(String[] args){
    new ReaderThread().start();
    ready = true;
    number = 30;
  }
}
           

該線程會持續循環下去,因為讀線程可能永遠都看不到ready值,另一種更奇怪的現象,可能會輸出0,因為讀線程

可能看到了ready值,但是沒有看到之後寫入的number值。

//非線程安全的可變整數類
@NotThreadSafe
public class MutableInteger{
  private int value;

  public int get(){
    return value;
  }

  public void set(int value){
    this.value = value;
  }
}
           

該對象不是線程安全的,方法沒有做同步的情況下,當某個線程調用set方法的時候,另一個正在調用get的線程可能會看到更新後的value值,也可能看不到

//線程安全的可變整數類
@ThreadSafe
public class SynchronizedInteger{
  private int value;

  public synchronized int get(){
    return value;
  }

  public synchronized set(int value){
    this.value = value;
  }
}