方法內的變數為執行緒安全——T2101
阿新 • • 發佈:2021-01-13
package 物件及變數的併發訪問2;
/**
* 方法內的變數為執行緒安全
*
* 非執行緒安全問題存在於例項變數中,對於方法內部的私有變數,則不會存在非執行緒
* 安全問題,結果是“執行緒安全”的。
*
* 結果分析 : 方法中的變數不存在非執行緒安全問題,永遠都是執行緒安全的,這是因為方法內部的變數具有私有特性。
*/
/**
* 測試
*/
class HasSelfPrivateNumT211 {
public void addI(String userName){
try {
int num=0;
if(userName.equals("a")){
num=100;
System.out.println("a set over!");
Thread.sleep(2000);
}else {
num=200;
System.out.println("b set over!");
}
System.out.println(userName+"num="+num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadAT211 extends Thread{
private HasSelfPrivateNumT211 numT2211;
public ThreadAT211(HasSelfPrivateNumT211 numT2211){
super ();
this.numT2211=numT2211;
}
@Override
public void run() {
super.run();
numT2211.addI("a");
}
}
class ThreadBT211 extends Thread{
private HasSelfPrivateNumT211 numT2211;
public ThreadBT211(HasSelfPrivateNumT211 numT2211){
super();
this.numT2211=numT2211;
}
@Override
public void run() {
super.run();
numT2211.addI("b");
}
}
/**
* 執行
*/
class RunT211 {
public RunT211(){
HasSelfPrivateNumT211 numT2211=new HasSelfPrivateNumT211();
ThreadAT211 at2211=new ThreadAT211(numT2211);
at2211.start();
ThreadBT211 bt2211=new ThreadBT211(numT2211);
bt2211.start();
}
}
public class T2101 {
public static void main(String[] args) {
RunT211 runT211 =new RunT211();
}
}