php多线程 static变量,java多线程 - 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());

}

}

}

上面是我对静态变量的线程安全方案,就是在设置值的时候开启一个线程同步锁的机制,不知道这样是否有效,我在测试的时候,程序死锁过。

请问有什么有效的方法可以测试吗或者解决我当前的问题,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值