Java 并发之共享变量

来源:互联网 发布:电竞椅品牌 知乎 编辑:程序博客网 时间:2024/05/22 03:07

                    同步访问共享的可变数据

    同步的意义有两个方面,之前一直以为只是为了操作的互斥性,保持状态一致,理解太浅显,需要深入研究。

            一、保持对象状态一致性,即同步可以阻止一个线程看到对象处于不一致的状态中,当一个线程访问同步对

象时,可阻止其他线程对该对象进行访问,从而观察到对象内部不一致的状态;

    二、保证进入同步方法或者同步代码块的每个线程,都看到由同一个锁保护的之前的所有修改。

             示例一、

     如果期望1s中后,backgroudThread线程能够正常退出,在某些机器上可能会失败,因为主进程将stopRequested设置为true的状态,backgroudThread不一定能及时看到。

    public class StopThread     {private static boolean stopRequested;//public static synchronized void requestStop()//{//stopRequested = true;//}////public static synchronized boolean stopRequested()//{//return stopRequested;//}public static void main(String[] args) throws InterruptedException{Thread backgroudThread = new Thread(new Runnable(){public void run(){int i = 0;while(!stopRequested){i++;System.out.println("i: " + i);}System.out.println("out!!!");}});backgroudThread.start();TimeUnit.SECONDS.sleep(1);//requestStop();stopRequested = true;}    }


 

        示例二、

   用同步来解决这个问题,通过同步,backgroudThread线程每次读的状态值stopRequested都能保证是其他线程已经修改过的。

    public class StopThread     {private static boolean stopRequested;public static synchronized void requestStop(){stopRequested = true;}public static synchronized boolean stopRequested(){return stopRequested;}public static void main(String[] args) throws InterruptedException{Thread backgroudThread = new Thread(new Runnable(){public void run(){int i = 0;while(!stopRequested()){i++;System.out.println("i: " + i);}System.out.println("out!!!");}});backgroudThread.start();TimeUnit.SECONDS.sleep(1);requestStop();}    }


         另外,volatile也可以保证它所修饰的对象的修改都能被立即写入主内存,从而达到同步的效果,如果只需要线程之间通信,而不用互斥,volatile是一种可以接受的同步形式,但使用要谨慎。

   java语言规范保证所有基本数据类型的读写操作都是原子操作,long和double除外,因为64位数值会被分成两个32位值来操作。

          最好的方法:要么共享不可变的数据,要么压根不共享,即将可变数据限制在单个线程中。

   注:java内存模型(JMM),深入理解java内存模型。

 

 

 

 

 

0 0