Java 线程

@ 等待结果返回的线程

不需要返回结果的线程

public Runnable getThread(int i) {
    return () -> {
        try {
            Thread.sleep(1 * 10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "----" + i);
    };
}

@Test
public void test() {
    ExecutorService executorService = Executors.newFixedThreadPool(10);//设定线程池,减少线程创建,浪费资源
    long start=System.currentTimeMillis();//获取当前时间
    for (int i = 0; i <= 100; i++) {
        executorService.execute(getThread(i));
    }
    System.out.println(System.currentTimeMillis()-start);//计算执行时间差
    executorService.shutdown();
}

带有返回结果的线程

@Test
public void getNum() throws ExecutionException, InterruptedException {
    Callable<Integer> callable = () -> {
        Thread.sleep(1 * 1000);
        return 2 * 20 + 10;
    };
    FutureTask<Integer> futureTask = new FutureTask<>(callable);
    new Thread(futureTask).start();
    System.out.println(futureTask.get() + "");
}

带有返回结果的线程和线程池一起使用

public void getString() {
    List<String> list = new ArrayList();
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    long start=System.currentTimeMillis();
    for (int i = 0; i <= 100; i++) {
        Future<String> future = executorService
                .submit(() -> {
                    Thread.sleep(1 * 10);
                    return "Hello World" + Thread.currentThread().getName();
                });
        try {
            list.add(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    for (String s: list) {
        System.out.println(s + "");
    }
    executorService.shutdown();
    System.out.println(System.currentTimeMillis()-start);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值