import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ScheduledExecuterServicePractice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Started");
NumberManager nm= new NumberManager();
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
for(int i=0;i<10;i ) {
newFixedThreadPool.submit(()->
System.out.println(Thread.currentThread().toString() " " nm.incrementCount()));
}
newFixedThreadPool.shutdown();
}
}
class NumberManager{
//int count =0;
AtomicInteger count = new AtomicInteger();
public int incrementCount() {
return count.incrementAndGet();
}
}
The output is
Started
Thread[pool-2-thread-3,5,main] 1
Thread[pool-2-thread-4,5,main] 4
Thread[pool-2-thread-1,5,main] 3
Thread[pool-2-thread-5,5,main] 5
Thread[pool-2-thread-2,5,main] 2
Thread[pool-2-thread-6,5,main] 6
Thread[pool-2-thread-7,5,main] 8
Thread[pool-2-thread-8,5,main] 7
Thread[pool-2-thread-9,5,main] 9
Thread[pool-2-thread-10,5,main] 10
My question is how the value 4 is printed before 3. I have used atomic class. So only one thread can do the operation at on time.
I have printed the thread name and the count. So if the count is 0 and one thread comes and make it 1 so that should be displayed in the terminal right? then if another thread comes and executes then the value 2 will be printed ? But Here I don't understand.
CodePudding user response:
The reason is below code
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
for(int i=0;i<10;i ) {
newFixedThreadPool.submit(()->
System.out.println(Thread.currentThread().toString() " " nm.incrementCount()));
}
The 10 threads are not guarantee to execute in order:
System.out.println
andnm.incrementCount()
are not guaranteed in the same order
A more details explanation:
Thread-1
invokenm.incrementCount()
,the value is 1Thread-2
invokenm.incrementCount()
,the value is 2Thread-2
print value ofnm.incrementCount()
,the output is 2Thread-1
print value ofnm.incrementCount()
,the output is 1
If you want to them to print in order,you can use newFixedThreadPool
or newSingleThreadExecutor()
instead
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(1);
//ExecutorService newFixedThreadPool = Executors.newSingleThreadExecutor();
for(int i=0;i<10;i ) {
newFixedThreadPool.submit(()->
System.out.println(Thread.currentThread().getName() " " nm.incrementCount()));
}