public class Counter {
public static int threadCount=1000;
public static int count=0;
public static CountDownLatch start = new CountDownLatch(threadCount);
public static CountDownLatch end =new CountDownLatch(threadCount);
public static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args){
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Counter.inc();
end.countDown();
}
}).start();
start.countDown();
}
try {
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Counter.count);
}
}

解决方案 »

  1.   

    inc不是线程不安全,加上同步关键字即可
      

  2.   

    因为inc方法的执行不是原子的,可以给它加上synchronized关键字。
      

  3.   

    除了楼上方法,将count变成int的原子类:AtomicInteger也行
      

  4.   

    没有同步,所以线程之间互不影响,可以给它加上synchronized关键字。
      

  5.   

    多线程之间的,会出现互斥争抢临界资源的问题,需要进行同步,来解决,做法是在某个线程访问临界资源时,要加把锁(synchironized),其他想访问此资源的线程,需要等待。