I have following worker class -
public class Worker implements Runnable {
private int workId;
public Worker(int workId) {
this.workId = workId;
}
private int count = 0;
private synchronized void increment() {
System.out.println("Work id: " + workId);
System.out.println("Incrementing...");
Thread.sleep(5000);
count++;
System.out.println("Incremented");
}
@Override
public void run() {
increment();
}
}
I have following main method -
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 10; i++) {
executorService.submit(new Worker(i));
}
executorService.shutdown();
System.out.println("All tasks submitted");
executorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("All tasks completed");
Here increment()
has been synchronized. So when 1 thread is occupying it another thread has to wait until that thread leaves the lock.
But when I am submitting the work using a thread pool of 2 threads, both threads seem to be using increment()
at the same time.
So here how can I force the two threads to use the increment()
method only one at a time?