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

java多线程 demo ,包含带返回值的Callable和不带返回值的Runnable_第1张图片

你可能感兴趣的:(java)