I'm new with thread pools, and learning to use synchronized
This code has the issue of race condition:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit ;
public class Counter implements Runnable{
int count;
public Counter(){
count=0;
}
public void run(){
count++;
}
public static void main(String[] args) throws
InterruptedException{
ExecutorService exec=Executors.newFixedThreadPool(2);
Counter task=new Counter();
for (int i=0;i<1000;i++ ) {
exec.execute(task);
}
exec.shutdown();
exec.awaitTermination(50L,TimeUnit.SECONDS);
System.out.println(task.count);
}
}
In this code race condition is taken cared off:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit ;
public class Counter implements Runnable{
int count;
public Counter(){
count=0;
}
public synchronized void run(){
count++;
}
public static void main(String[] args) throws
InterruptedException{
ExecutorService exec=Executors.newFixedThreadPool(2);
Counter task=new Counter();
for (int i=0;i<1000;i++ ) {
exec.execute(task);
}
exec.shutdown();
exec.awaitTermination(50L,TimeUnit.SECONDS);
System.out.println(task.count);
}
}
But I think in second implementation the there's no point using threads as the execution will be "sort of" sequential. As only one thread out of the two will have the access of the object monitor while the other one will wait until execution of first thread and will be the monitor's access only when the first one is done. This sounds like sequential.
Please correct me if I'm wrong. Any help is highly appreciated.