0

以下是代码:我已使运行代码同步,但在运行使用 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 。请告诉我为什么这不起作用?

4

0 回答 0