java如何实现静态变量多线程安全问题
问题,如题!
我先说我目前的方案(我感觉不靠谱,但是又不知道如何测试):
public class SaveDatabasePlanCache {
private static Integer vehicleSum=0;
public static Integer getVehicleSum() {
return vehicleSum;
}
public synchronized static void setVehicleSum(Integer vehicleSum) {
SaveDatabasePlanCache.vehicleSum = vehicleSum;
}
}
测试方案:
TestThread t1=new TestThread("线程1: ");
TestThread t2=new TestThread("线程2: ");
TestThread t3=new TestThread("线程3: ");
TestThread t4=new TestThread("线程4: ");
ExecutorService service=Executors.newFixedThreadPool(4);
service.submit(t1);
service.submit(t2);
service.submit(t3);
service.submit(t4);
线程代码:
public void run() {
int sum=0;
boolean flag=true;
while(flag){
sum=SaveDatabasePlanCache.getVehicleSum();
if(sum==10000){
System.out.println(new Date().toLocaleString()+" "+title+"不执行");
flag=false;
}else{
SaveDatabasePlanCache.setVehicleSum(sum+1);
System.out.println(new Date().toLocaleString()+" "+title+SaveDatabasePlanCache.getVehicleSum());
}
}
}
上面是我对静态变量的线程安全方案,就是在设置值的时候开启一个线程同步锁的机制,不知道这样是否有效,我在测试的时候,程序死锁过。
请问有什么有效的方法可以测试吗或者解决我当前的问题,谢谢!
java java多线程 线程安全 静态方法 synchronized
费诺瓦.卡塔
9 years, 4 months ago
Answers
问题已经解决,我把缓存类的属性改为了原子数据类型代码如下:
public static AtomicInteger vehicleSum=new AtomicInteger(0);
public static AtomicInteger vehicleCurrent=new AtomicInteger(1);
public static AtomicInteger vehicle32Sum=new AtomicInteger(0);
public static AtomicInteger vehicle32Current=new AtomicInteger(1);
public static AtomicInteger vehicle33Sum=new AtomicInteger(0);
public static AtomicInteger vehicle33Current=new AtomicInteger(1);
public static AtomicInteger vehicleWdSum=new AtomicInteger(0);
public static AtomicInteger vehicleWdCurrent=new AtomicInteger(1);
public static AtomicInteger vehicleZdSum=new AtomicInteger(0);
public static AtomicInteger vehicleZdCurrent=new AtomicInteger(1);
么么艾萨克
answered 9 years, 4 months ago