共享变量的可以见性

来源:互联网 发布:无主之地2mac汉化 编辑:程序博客网 时间:2024/06/13 21:17
package first;import java.util.concurrent.TimeUnit;public class NoVisible {    private static boolean ready = false;    private static int number=10;    private static Object lock = new Object();    static class ReaderThread extends Thread {@Overridepublic void run() {// 读线程,没有加锁,会一直读,即使test方法在执行,所以 读与 set并不互为原子操作,因为 读的时候没有和写加同一把锁    do {System.out.println(number);Thread.yield();    } while (!ready);}    }    public static void main(String args[]) {new ReaderThread().start();try {    TimeUnit.NANOSECONDS.sleep(1);}catch(InterruptedException e){    }set();    }    public synchronized static void set() {number = 19;System.out.println("已经改过了...");//改过之后立即通知try {    TimeUnit.NANOSECONDS.sleep(1); // 这样       // reader读到的可能会是过期的数据,因为在读的过程中没有加锁,因为在这个方法sleep时,读线程还会一直读,因为读的时候并没有加锁} catch (InterruptedException e) {}number = 20;System.out.println("又改了一次...");ready = true;    }}