0

Following is the code: I have made run code synchronised but on running the 3 threads created using ExecutorService, Synchronisation is not working. All thread are accessing the thread at same time. I don't know what is wrong here:

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();

       }
    } 

When i executed this code , I go the following result:

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

Why synchronisation is not working in this case? what I am doing wrong? All thread of ExecutorService are decrementing CountDown at same time and that's why I think instead of printing 10,9,8,7,6,5,4,3,2,1, Its directly printing 7 then 4 then 1 and 0 . Please Tell me why this is not working ?

shmosel
  • 49,289
  • 6
  • 73
  • 138
Novice
  • 49
  • 11

0 Answers0