Can Future get thread return value to make threads execute in sequence?

Thread unsafe method getNext()

import net.jcip.annotations.NotThreadSafe;

@NotThreadSafe
public class UnSafeSequence 
{
    
    private int value;
    
    public int getNext()
    {
        return value++;
    }
}

1. The initial purpose is to test the return value of the getNext() method executed by the thread pool

The main function is as follows:

public class UnSafeQequenceTest
{

    /**
     * @throws ExecutionException
     * @throws InterruptedException
     */

    public static void main(String[] args)
    {
        UnSafeSequence unSafeSequence = new UnSafeSequence();

        ExecutorService executors = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++ )
        {
            executors.submit(() -> System.out.println(unSafeSequence.getNext()));
        }
        executors.shutdown();
    }

}

The results were as disorganized as expected:

2. By the way, use Future to receive the results of thread execution

The main method is modified as follows:

public class UnSafeQequenceTest
{

    /**
     * @throws ExecutionException
     * @throws InterruptedException
     */

    public static void main(String[] args)
        throws InterruptedException, ExecutionException
    {
        UnSafeSequence unSafeSequence = new UnSafeSequence();
        List<Integer> lstNumber = new ArrayList<Integer>();

        ExecutorService executors = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++ )
        {
            Future<Integer> future = executors.submit(() -> unSafeSequence.getNext());
            Integer temp = future.get();
            System.out.println(temp);
            lstNumber.add(temp);
        }
        Integer max = 0;
        for (Integer e : lstNumber)
        {
            if (e >= max)
            {
                max = e;
            }
            else
            {
                System.out.println(e);
                System.out.println(lstNumber);
            }
        }
        executors.shutdown();
    }

}

The result of the execution is:

There's no problem with the order of the output, WTF? It's not normal

Is it caused by the main thread blocking when the Future object gets the thread return result?

Posted by Ace_Online on Sat, 04 Jan 2020 17:04:49 -0800