Future獲取線程返回值能使線程順序執行?

線程非安全的方法getNext()java

import net.jcip.annotations.NotThreadSafe;

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

一、最開始的目的是測試線程池執行getNext()方法的返回值安全

main函數以下:函數

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

}

結果如預期般是亂序的:測試

二、順便試一下采用Future來接收線程執行的結果線程

main方法修改以下:code

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

}

而後執行的結果是:對象

輸出的順序沒有絲毫問題,WTF?這好像不太正常啊 blog

難道是Future對象獲取線程返回結果時致使的主線程阻塞引發的之外效果?ip

相關文章
相關標籤/搜索