2.1.1方法内的变量为线程安全
Posted 成功的路上总是离不开贵人的帮助,名师的指点和小人的刺激。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.1.1方法内的变量为线程安全相关的知识,希望对你有一定的参考价值。
非线程安全的问题存在于实例变量中,如果是方法内部的私有变量,则不存在非线程安全的问题,所以也就是线程安全了。
测试
1 package com.cky.bean; 2 3 /** 4 * Created by chenkaiyang on 2017/12/4. 5 */ 6 public class SelfPrivateNum { 7 8 public void addI(String usrName) { 9 try { 10 int num =0; 11 if (usrName.equals("a")) { 12 num =100; 13 System.out.println("a over"); 14 Thread.sleep(2000); 15 } else { 16 num= 200; 17 System.out.println("b over"); 18 19 } 20 System.out.println(usrName + " num="+ num); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 } 25 }
1 package com.cky.thread; 2 3 import com.cky.bean.SelfPrivateNum; 4 5 /** 6 * Created by chenkaiyang on 2017/12/4. 7 */ 8 public class ThreadA extends Thread{ 9 private SelfPrivateNum sn; 10 public ThreadA (SelfPrivateNum sn) { 11 this.sn = sn; 12 } 13 @Override 14 public void run() { 15 super.run(); 16 sn.addI("a"); 17 } 18 }
1 package com.cky.thread; 2 3 import com.cky.bean.SelfPrivateNum; 4 5 /** 6 * Created by chenkaiyang on 2017/12/4. 7 */ 8 public class ThreadB extends Thread{ 9 private SelfPrivateNum sn; 10 public ThreadB (SelfPrivateNum sn) { 11 this.sn = sn; 12 } 13 @Override 14 public void run() { 15 super.run(); 16 sn.addI("b"); 17 } 18 }
1 package com.cky.test; 2 3 import com.cky.bean.SelfPrivateNum; 4 import com.cky.thread.ThreadA; 5 import com.cky.thread.ThreadB; 6 7 /** 8 * Created by chenkaiyang on 2017/12/2. 9 */ 10 public class Test { 11 public static void main(String[] args){ 12 SelfPrivateNum sn = new SelfPrivateNum(); 13 ThreadA threadA = new ThreadA(sn); 14 ThreadB threadB = new ThreadB(sn); 15 threadA.start(); 16 threadB.start(); 17 } 18 }
D:\it\jdk1.8\bin\java -Didea.launcher.port=7532 "-Didea.launcher.bin.path=D:\it\idea\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\it\jdk1.8\jre\lib\charsets.jar;D:\it\jdk1.8\jre\lib\deploy.jar;D:\it\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\it\jdk1.8\jre\lib\ext\cldrdata.jar;D:\it\jdk1.8\jre\lib\ext\dnsns.jar;D:\it\jdk1.8\jre\lib\ext\jaccess.jar;D:\it\jdk1.8\jre\lib\ext\jfxrt.jar;D:\it\jdk1.8\jre\lib\ext\localedata.jar;D:\it\jdk1.8\jre\lib\ext\nashorn.jar;D:\it\jdk1.8\jre\lib\ext\sunec.jar;D:\it\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\it\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\it\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\it\jdk1.8\jre\lib\ext\zipfs.jar;D:\it\jdk1.8\jre\lib\javaws.jar;D:\it\jdk1.8\jre\lib\jce.jar;D:\it\jdk1.8\jre\lib\jfr.jar;D:\it\jdk1.8\jre\lib\jfxswt.jar;D:\it\jdk1.8\jre\lib\jsse.jar;D:\it\jdk1.8\jre\lib\management-agent.jar;D:\it\jdk1.8\jre\lib\plugin.jar;D:\it\jdk1.8\jre\lib\resources.jar;D:\it\jdk1.8\jre\lib\rt.jar;F:\springboot\threaddemo\out\production\threaddemo;D:\it\idea\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test a over b over b num=200 a num=100
结果分析:
方法变量中不存在非线程安全的问题,永远都是线程安全的,这是方法内部变量是私有造成的。
以上是关于2.1.1方法内的变量为线程安全的主要内容,如果未能解决你的问题,请参考以下文章