//非同步共享变量
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;
}
}