赞
踩
频繁的创建\销毁线程就会降低我们的执行效率,这时候就引入了线程池,一个可以容纳多个线程的容器。
线程池工厂类,推荐使用这个
创建线程池方法一
- public class Test {
- public static void main(String[] args) {
- //创建线程池
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- //提交任务,并且执行任务
- MyThread myThread = new MyThread();
- executorService.submit(myThread);
- executorService.submit(myThread);
- executorService.submit(myThread);
-
- //销毁线程池(实际开发中一般不销毁)
- executorService.shutdown();
- }
- }
-
- class MyThread implements Runnable{
-
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName()+"执行任务");
- }
- }

创建线程池方法二,有返回值Callable
- public class Test {
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- //创建线程池
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- //提交任务,并且执行任务
- MyThread2 myThread2 = new MyThread2();
- //Callable接口可以有返回值
- Future<String> stringFuture = executorService.submit(myThread2);
- //返回值结果
- System.out.println(stringFuture.get());
-
- //销毁线程池(实际开发中一般不销毁)
- executorService.shutdown();
- }
- }
- class MyThread2 implements Callable<String> {
- @Override
- public String call() throws Exception {
- System.out.println("执行一个任务");
- return "666666";
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。