package com.freeflying.thread.sync;
/**
* @ClassName: InstanceVarThreadSafe
* @Description:实例的变量是线程不安全的
* @author freeflying
* @date 2018年6月25日
*/
public class InstanceVarThreadNotSafe {
public static void main(String[] args) {
InstanceVarThreadNotSafeEx notSafeEx=new InstanceVarThreadNotSafeEx();
InstanceVarThreadNotSafeA safeA=new InstanceVarThreadNotSafeA(notSafeEx);
safeA.start();
InstanceVarThreadNotSafeB safeB=new InstanceVarThreadNotSafeB(notSafeEx);
safeB.start();
}
}
class InstanceVarThreadNotSafeEx{
int num = 0;
public void add(String username) {
try {
if("a".equals(username)) {
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 (Exception e) {
// TODO: handle exception
}
}
}
class InstanceVarThreadNotSafeA extends Thread{
private InstanceVarThreadNotSafeEx safe;
public InstanceVarThreadNotSafeA(InstanceVarThreadNotSafeEx safe) {
this.safe=safe;
}
@Override
public void run() {
safe.add("a");
}
}
class InstanceVarThreadNotSafeB extends Thread{
private InstanceVarThreadNotSafeEx safe;
public InstanceVarThreadNotSafeB(InstanceVarThreadNotSafeEx safe) {
this.safe=safe;
}
@Override
public void run() {
safe.add("b");
}
}
结果:
a set over
b set over
b num = 200
a num = 200
结论:可以在add()前面添加synchronized来避免线程不安全