1. 程式人生 > >java執行緒池——接收執行緒執行後返回的結果

java執行緒池——接收執行緒執行後返回的結果

package com.xueyoucto.xueyou;

import java.util.concurrent.Callable;

public class ThreadReturnValue implements Callable {
    @Override
    public Object call() throws Exception {
        int temp = 0;
        StringBuffer sb = new StringBuffer("");
        synchronized (App.GLOBALARRAY) {
            for (int i = 0; i < App.GLOBALARRAY.length; i++) {
                System.out.println(Thread.currentThread().getName() + "\n" + App.GLOBALARRAY[i]);
                App.GLOBALARRAY[i] += 1;
                temp += App.GLOBALARRAY[i];
                sb.append("+").append(App.GLOBALARRAY[i]);
            }
        }
        return sb.toString() + "=" + temp;
    }
}
package com.xueyoucto.xueyou;


import java.util.concurrent.*;

/**
 * Hello world!
 */
public class App {
    public static int[] GLOBALARRAY = new int[50];

    public static ThreadLocal<String[]> TLGLOBALARRAY = new ThreadLocal<String[]>() {
        @Override
        protected String[] initialValue() {
            String[] temp = new String[50];
            for (int i = 0; i < temp.length; i++) {
                temp[i] = String.valueOf(i + 100);
            }
            return temp;
        }
    };

    static {
        for (int i = 0; i < GLOBALARRAY.length; i++) {
            GLOBALARRAY[i] = i;
        }
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        Future<String> future = pool.submit(new ThreadReturnValue());
        Future<String> future2 = pool.submit(new ThreadReturnValue());
        Future<String> future3 = pool.submit(new ThreadReturnValue());
        pool.shutdown(); // 不允許再想執行緒池中增加執行緒
        //判斷是否所有執行緒已經執行完畢
        try {
            boolean isFinish = pool.awaitTermination(1, TimeUnit.HOURS);
            System.out.println(isFinish + "==========================");
            //如果沒有執行完
            if (!isFinish) {
                //執行緒池執行結束 不在等待執行緒執行完畢,直接執行下面的程式碼
                pool.shutdownNow();
            }
            String r = future.get();
            String r2 = future2.get();
            String r3 = future3.get();

            System.out.println(r);
            System.out.println(r2);
            System.out.println(r3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //只給執行緒池中的執行緒1小時,然後就繼續執行
        System.out.println("it is ok !!!");
    }
}

執行結果: