线程安全和非线程安全实例:
线程安全代码实例:
public class ThreadSafe {
public static void main(String[] args) {
HasSelf numself=new HasSelf();
threadA aThreadA=new threadA(numself);
aThreadA.start();
threadB bThreadB=new threadB(numself);
bThreadB.start();
}
}
class HasSelf{
//private int num=0;
public void addI(String username){
try {
int num=0;
if(username.equals("a")){
num=100;
System.out.println("a set over");
Thread.sleep(1);
}
else {
num=200;
System.out.println("b set over");
}
System.out.println(username+"num= "+num);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class threadA extends Thread{
private HasSelf numself;
public threadA(HasSelf numself) {
super();
this.numself=numself;
}
@Override
public void run() {
super.run();
numself.addI("a");
}
}
class threadB extends Thread{
private HasSelf numself;
public threadB(HasSelf numself) {
super();
this.numself=numself;
}
@Override
public void run() {
super.run();
numself.addI("b");
}
}
执行结果:
a set over
b set over
anum= 100
bnum= 200
线程非安全:
把sleep那一句注释掉
执行结果:
a set over
anum= 100
b set over
bnum= 200
把//private int num=0;注释去掉,把int num=0注释掉
执行结果:
a set over
b set over
bnum= 200
anum= 200
自己好好体会下~~
提示:多个线程共同访问一个对象中实例变量时,则可能出现非线程安全,同时若线程访问多个实例变量,则可能产生交叉情况
线程安全和非线程安全的理解
最新推荐文章于 2022-03-23 23:21:01 发布