多线程存在资源共享以及数据不一致的问题,你看下面这篇是怎么写的
操作的变量volatile保证可见性,操作流程加锁保证原子性
可以使用原子类 AtomicInteger 来解决
public class Ex6 {
AtomicInteger piaoshu = new AtomicInteger(50);
public static void main(String[] args) {
Ex6 ex6 = new Ex6();
for (int i=1; i<6; i++){
new Thread(ex6::shoupiao,i+"号窗口").start();
}
}
void shoupiao(){
while(true){
synchronized (this){
if (piaoshu.get()>0) {
piaoshu.decrementAndGet();//decrementAndGet()原子地递减当前值,具有由 VarHandle.getAndAdd 指定的记忆效果。等效于 addAndGet(-1)
System.out.printf("%s:售出一张,剩余%d张%n", Thread.currentThread().getName(),piaoshu.get());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}