以下是代码: 我已经使运行代码同步但在运行使用ExecutorService创建的3个线程时,同步不起作用。所有线程都在同时访问该线程。我不知道这里有什么问题:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class cpu implements Runnable {
private CountDownLatch latch;
public cpu(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
synchronized(this){
System.out.println("Started");
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
ex.printStackTrace();
}
latch.countDown();
System.out.println("Value of CountDownLatch after each
CountDown:" + latch.getCount());
}
}
public static void main(String[] args){
CountDownLatch latch = new CountDownLatch(10);
ExecutorService executor = Executors.newFixedThreadPool(3);
for(int i=0; i<11; i++ ){
executor.submit(new cpu(latch));
}
try {
latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Completed");
executor.shutdown();
}
}
当我执行此代码时,我得到以下结果:
Started
Started
Started
Value of CountDownLatch after each CountDown:7
Value of CountDownLatch after each CountDown:7
Value of CountDownLatch after each CountDown:7
Started
Started
Started
Value of CountDownLatch after each CountDown:4
Value of CountDownLatch after each CountDown:4
Value of CountDownLatch after each CountDown:4
Started
Started
Started
Value of CountDownLatch after each CountDown:2
Value of CountDownLatch after each CountDown:2
Value of CountDownLatch after each CountDown:1
Started
Started
Value of CountDownLatch after each CountDown:0
Completed
Value of CountDownLatch after each CountDown:0
为什么在这种情况下同步不起作用?我做错了什么? ExecutorService的所有线程同时递减CountDown,这就是为什么我认为而不是打印10,9,8,7,6,5,4,3,2,1,它直接打印7然后4然后1和0。请告诉我为什么这不起作用?