volatile关键字

阅读更多
volatile:使变量在多个线程间可见


public class VolatileDemo3 {
/**volatile*/
public volatile  int inc = 0;
public synchronized void increase() {
      inc++;
}
public static void main(String[] args) throws InterruptedException {
final VolatileDemo3 test = new VolatileDemo3();
        for(int i=0;i<10;i++){
            new Thread(){
                public void run() {
                    for(int j=0;j<1000;j++)
                        test.increase();
                };
            }.start();
        }
        
        while(Thread.activeCount()>1)  //保证前面的线程都执行完
        Thread.yield();//yield()的作用是让步。它能让当前线程由“运行状态”进入到“就绪状态”
        System.out.println(test.inc);
}

}

你可能感兴趣的:(java)