• Java中处理线程同步


    引自:http://blog.csdn.net/aaa1117a8w5s6d/article/details/8295527http://m.blog.csdn.net/blog/undoner/12849661

    静态变量:线程非安全。

    静态变量即类变量,位于方法区,为所有对象共享,共享一份内存,一旦静态变量被修改,其他对象均对修改可见,故线程非安全。

    实例变量:单例模式(只有一个对象实例存在)线程非安全,非单例线程安全。

    实例变量为对象实例私有,在虚拟机的堆中分配,若在系统中只存在一个此对象的实例,在多线程环境下,“犹如”静态变量那样,被某个线程修改后,其他线程对修改均可见,故线程非安全;如果每个线程执行都是在不同的对象中,那对象与对象之间的实例变量的修改将互不影响,故线程安全。

    局部变量:线程安全。

    每个线程执行时将会把局部变量放在各自栈帧的工作内存中,线程间不共享,故不存在线程安全问题。

    静态变量线程安全问题模拟:

    ----------------------------------------------------------------------------------

    Java代码  收藏代码
    1. /**  
    2.   * 线程安全问题模拟执行  
    3.   *  ------------------------------  
    4.   *       线程1      |    线程2  
    5.   *  ------------------------------  
    6.   *   static_i = 4;  | 等待  
    7.   *   static_i = 10; | 等待  
    8.   *    等待          | static_i = 4;  
    9.   *   static_i * 2;  | 等待  
    10.   *  ----------------------------- 
    11.  * */  
    12. public class Test implements Runnable  
    13. {  
    14.     private static int static_i;//静态变量   
    15.       
    16.     public void run()  
    17.     {  
    18.         static_i = 4;  
    19.         System.out.println("[" + Thread.currentThread().getName()  
    20.                 + "]获取static_i 的值:" + static_i);  
    21.         static_i = 10;  
    22.         System.out.println("[" + Thread.currentThread().getName()  
    23.                 + "]获取static_i*3的值:" + static_i * 2);  
    24.     }  
    25.       
    26.     public static void main(String[] args)  
    27.     {  
    28.         Test t = new Test();  
    29.         //启动尽量多的线程才能很容易的模拟问题   
    30.         for (int i = 0; i < 3000; i++)  
    31.         {  
    32.             //t可以换成new Test(),保证每个线程都在不同的对象中执行,结果一样   
    33.             new Thread(t, "线程" + i).start();  
    34.         }  
    35.     }  
    36. }  

    根据代码注释中模拟的情况,当线程1执行了static_i = 4;  static_i = 10; 后,线程2获得执行权,static_i = 4; 然后当线程1获得执行权执行static_i * 2;  必然输出结果4*2=8,按照这个模拟,我们可能会在控制台看到输出为8的结果。

    写道
    [线程27]获取static_i 的值:4 
    [线程22]获取static_i*2的值:20 
    [线程28]获取static_i 的值:4 
    [线程23]获取static_i*2的值:8 
    [线程29]获取static_i 的值:4 
    [线程30]获取static_i 的值:4 
    [线程31]获取static_i 的值:4 
    [线程24]获取static_i*2的值:20

     看红色标注的部分,确实出现了我们的预想,同样也证明了我们的结论。

     

    实例变量线程安全问题模拟:

    ----------------------------------------------------------------------------------

    Java代码  收藏代码
    1. public class Test implements Runnable  
    2. {  
    3.     private int instance_i;//实例变量  
    4.       
    5.     public void run()  
    6.     {  
    7.         instance_i = 4;  
    8.         System.out.println("[" + Thread.currentThread().getName()  
    9.                 + "]获取instance_i 的值:" + instance_i);  
    10.         instance_i = 10;  
    11.         System.out.println("[" + Thread.currentThread().getName()  
    12.                 + "]获取instance_i*3的值:" + instance_i * 2);  
    13.     }  
    14.       
    15.     public static void main(String[] args)  
    16.     {  
    17.         Test t = new Test();  
    18.         //启动尽量多的线程才能很容易的模拟问题   
    19.         for (int i = 0; i < 3000; i++)  
    20.         {  
    21.             //每个线程对在对象t中运行,模拟单例情况  
    22.             new Thread(t, "线程" + i).start();  
    23.         }  
    24.     }  
    25. }  

     

    按照本文开头的分析,犹如静态变量那样,每个线程都在修改同一个对象的实例变量,肯定会出现线程安全问题。

    写道

    [线程66]获取instance_i 的值:10 
    [线程33]获取instance_i*2的值:20 
    [线程67]获取instance_i 的值:4 
    [线程34]获取instance_i*2的值:8 
    [线程35]获取instance_i*2的值:20 
    [线程68]获取instance_i 的值:4

     

    看红色字体,可知单例情况下,实例变量线程非安全。

     

    将new Thread(t, "线程" + i).start();改成new Thread(new Test(), "线程" + i).start();模拟非单例情况,会发现不存在线程安全问题。

     

     

    局部变量线程安全问题模拟:

    ----------------------------------------------------------------------------------

    Java代码  收藏代码
    1. public class Test implements Runnable  
    2. {  
    3.     public void run()  
    4.     {  
    5.         int local_i = 4;  
    6.         System.out.println("[" + Thread.currentThread().getName()  
    7.                 + "]获取local_i 的值:" + local_i);  
    8.         local_i = 10;  
    9.         System.out.println("[" + Thread.currentThread().getName()  
    10.                 + "]获取local_i*2的值:" + local_i * 2);  
    11.     }  
    12.       
    13.     public static void main(String[] args)  
    14.     {  
    15.         Test t = new Test();  
    16.         //启动尽量多的线程才能很容易的模拟问题  
    17.         for (int i = 0; i < 3000; i++)  
    18.         {  
    19.             //每个线程对在对象t中运行,模拟单例情况   
    20.             new Thread(t, "线程" + i).start();  
    21.         }  
    22.     }  
    23. }  

     

    控制台没有出现异常数据。

    **************************************************************

    为什么要线程同步?

      说到线程同步,大部分情况下, 我们是在针对“单对象多线程”的情况进行讨论,一般会将其分成两部分,一部分是关于“共享变量”,一部分关于“执行步骤”。

    如何控制线程同步

      既然线程同步有上述问题,那么我们应该如何去解决呢?针对不同原因造成的同步问题,我们可以采取不同的策略。

    1.控制共享变量

      我们可以采取3种方式来控制共享变量。

      (1)将“单对象多线程”修改成“多对象多线程”  

      上文提及,同步问题一般发生在“单对象多线程”的场景中,那么最简单的处理方式就是将运行模型修改成“多对象多线程”的样子,针对上面示例中的同步问题,修改后的代码如下:

    复制代码
     1 private static void sharedVaribleTest2() throws InterruptedException
     2 {
     3     Thread thread1 = new Thread(new MyRunner());
     4     Thread thread2 = new Thread(new MyRunner());
     5     thread1.setDaemon(true);
     6     thread2.setDaemon(true);
     7     thread1.start();
     8     thread2.start();
     9     thread1.join();
    10     thread2.join();
    11 }
    复制代码

      我们可以看到,上述代码中两个线程使用了两个不同的Runnable实例,它们在运行过程中,就不会去访问同一个全局变量。

      (2)将“全局变量”降级为“局部变量”

      既然是共享变量造成的问题,那么我们可以将共享变量改为“不共享”,即将其修改为局部变量。这样也可以解决问题,同样针对上面的示例,这种解决方式的代码如下:

    复制代码
     1 class MyRunner2 implements Runnable
     2 {
     3     public void run() 
     4     {
     5         System.out.println(Thread.currentThread().getName() + " Start.");
     6         int sum = 0;
     7         for (int i = 1; i <= 100; i++)
     8         {
     9             sum += i;
    10         }
    11         try {
    12             Thread.sleep(500);
    13         } catch (InterruptedException e) {
    14             e.printStackTrace();
    15         }
    16         System.out.println(Thread.currentThread().getName() + " --- The value of sum is " + sum);
    17         System.out.println(Thread.currentThread().getName() + " End.");
    18     }
    19 }
    20 
    21 
    22 private static void sharedVaribleTest3() throws InterruptedException
    23 {
    24     MyRunner2 runner = new MyRunner2();
    25     Thread thread1 = new Thread(runner);
    26     Thread thread2 = new Thread(runner);
    27     thread1.setDaemon(true);
    28     thread2.setDaemon(true);
    29     thread1.start();
    30     thread2.start();
    31     thread1.join();
    32     thread2.join();
    33 }
    复制代码

      我们可以看出,sum变量已经由全局变量变为run方法内部的局部变量了。

      (3)使用ThreadLocal机制

      ThreadLocal是JDK引入的一种机制,它用于解决线程间共享变量,使用ThreadLocal声明的变量,即使在线程中属于全局变量,针对每个线程来讲,这个变量也是独立的。

      我们可以用这种方式来改造上面的代码,如下所示:

    复制代码
     1 class MyRunner3 implements Runnable
     2 {
     3     public ThreadLocal<Integer> tl = new ThreadLocal<Integer>();
     4     
     5     public void run() 
     6     {
     7         System.out.println(Thread.currentThread().getName() + " Start.");
     8         for (int i = 0; i <= 100; i++)
     9         {
    10             if (tl.get() == null)
    11             {
    12                 tl.set(new Integer(0));
    13             }
    14             int sum = ((Integer)tl.get()).intValue();
    15             sum+= i;
    16             tl.set(new Integer(sum));
    17             try {
    18                 Thread.sleep(10);
    19             } catch (InterruptedException e) {
    20                 e.printStackTrace();
    21             }
    22         }
    23         
    24         System.out.println(Thread.currentThread().getName() + " --- The value of sum is " + ((Integer)tl.get()).intValue());
    25         System.out.println(Thread.currentThread().getName() + " End.");
    26     }
    27 }
    28 
    29 
    30 private static void sharedVaribleTest4() throws InterruptedException
    31 {
    32     MyRunner3 runner = new MyRunner3();
    33     Thread thread1 = new Thread(runner);
    34     Thread thread2 = new Thread(runner);
    35     thread1.setDaemon(true);
    36     thread2.setDaemon(true);
    37     thread1.start();
    38     thread2.start();
    39     thread1.join();
    40     thread2.join();
    41 }
    复制代码

      综上三种方案,第一种方案会降低多线程执行的效率,因此,我们推荐使用第二种或者第三种方案。

    2.控制执行步骤

      说到执行步骤,我们可以使用synchronized关键字来解决它。

    复制代码
     1 class MySyncRunner implements Runnable
     2 {
     3     public void run() {
     4         synchronized(this)
     5         {
     6             System.out.println(Thread.currentThread().getName() + " Start.");
     7             for(int i = 1; i <= 5; i++)
     8             {
     9                 System.out.println(Thread.currentThread().getName() + " Running step " + i);
    10                 try
    11                 {
    12                     Thread.sleep(50);
    13                 }
    14                 catch(InterruptedException ex)
    15                 {
    16                     ex.printStackTrace();
    17                 }
    18             }
    19             System.out.println(Thread.currentThread().getName() + " End.");
    20         }
    21     }
    22 }
    23 
    24 
    25 private static void syncTest2() throws InterruptedException
    26 {
    27     MySyncRunner runner = new MySyncRunner();
    28     Thread thread1 = new Thread(runner);
    29     Thread thread2 = new Thread(runner);
    30     thread1.setDaemon(true);
    31     thread2.setDaemon(true);
    32     thread1.start();
    33     thread2.start();
    34     thread1.join();
    35     thread2.join();
    36 }
    复制代码

      在线程同步的话题上,synchronized是一个非常重要的关键字。它的原理和数据库中事务锁的原理类似。我们在使用过程中,应该尽量缩减synchronized覆盖的范围,原因有二:1)被它覆盖的范围是串行的,效率低;2)容易产生死锁。我们来看下面的示例:

  • 相关阅读:
    Flask Mysql数据库连接
    Flask form前后端交互消息闪现
    Flask block继承和include包含
    Flask filter过滤器
    常规http状态码
    linux搭建hadoop环境
    inline-block布局代码
    JDBC4.0自动加载驱动器类
    用反射模拟Hibernate保存JavaBean
    深入ThreadLocal的内部机制
  • 原文地址:https://www.cnblogs.com/shz365/p/3766197.html
Copyright © 2020-2023  润新知