Young87

当前位置:首页 >个人收藏

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

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: 银行卡号四位分割

下一篇: Android波浪

精华推荐