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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值