1. 程式人生 > >java多執行緒 demo ,包含帶返回值的Callable和不帶返回值的Runnable

java多執行緒 demo ,包含帶返回值的Callable和不帶返回值的Runnable

輸入int,利用callable取得double值,再用runnable列印

import java.util.concurrent.*;

public class TestMultiThread {

    private static ExecutorService pool = null;

    // 獲取執行緒池單例,需要避免同步問題,即pool為null時兩執行緒同時呼叫該方法,就會出現一個執行緒池例項丟失
    private synchronized static ExecutorService getThreadPool() {
        int threadCount = 10;
        pool = Executors.newFixedThreadPool(threadCount);
        return pool;
    }

    /*帶返回值的callable*/
    private class ClassCallable implements Callable<Double> {
        int i;

        ClassCallable(int i) {
            this.i = i;
        }

        @Override
        public Double call() throws Exception {
            //開始執行耗時操作
            return Double.valueOf(i) + 0.1;
        }
    }

    /*不帶返回值的runnable*/
    private class ClassRunnable implements Runnable {
        Double j;

        ClassRunnable(Double j) {
            this.j = j;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "  開始執行ClassRunnable:" + j);
        }
    }

    public void getDoubeAndPrint(int i) {
        pool = getThreadPool();
        Double re = getDouble(i);
        pool.execute(new ClassRunnable(re));
    }

    private Double getDouble(int i) {
        Future<Double> future = pool.submit(new ClassCallable(i));
        Double result = null;
        try {
            System.out.println(Thread.currentThread().getName() + "  開始執行getDouble:" + i);
            result = future.get(1000, TimeUnit.MILLISECONDS); //任務處理超時時間設
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void main(String[] args) {
        TestMultiThread testMultiThread = new TestMultiThread();
        for (int i = 0; i < 10000; i++) {
            testMultiThread.getDoubeAndPrint(i);
        }
    }
}