线程池:线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用。
方法:

  • public static ExecutorService newFixedThreadPool(int nThreads)创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。

  • Future< ?> submit(Runnable task) 提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。

  • < T> Future< T> submit(Callable< T> task) 提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future。
  • void shutdown() 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。

线程池1

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int x = 0; x < 5; x++) {
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }
    }

}
        //创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
        ExecutorService es= Executors.newFixedThreadPool(3);
        //提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。 
        es.submit(new MyRunnable());
        es.submit(new MyRunnable());
        //启动一次顺序关闭,执行以前提交的任务,但不接受新任务。 
        es.shutdown();
输出:
pool-1-thread-2:0
pool-1-thread-1:0
pool-1-thread-1:1
pool-1-thread-1:2
pool-1-thread-2:1
pool-1-thread-2:2
pool-1-thread-1:3
pool-1-thread-1:4
pool-1-thread-2:3
pool-1-thread-2:4

线程池2:另外一种创建多线程的方式:


//Callable:是带泛型的接口。
//这里指定的泛型其实是call()方法的返回值类型。
//返回值类型是Object 的call
public class MyCallable implements Callable {

    @Override
    public Object call() throws Exception {
        for (int x = 0; x < 5; x++) {
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }
        return null;
    }

}
        //创建线程池对象
        ExecutorService es=Executors.newFixedThreadPool(2);
        //可以执行Runnable对象或者Callable对象代表的线程
        es.submit(new MyCallable());
        es.submit(new MyCallable());
        //结束
        es.shutdown();
输出:
pool-1-thread-1:0
pool-1-thread-1:1
pool-1-thread-1:2
pool-1-thread-1:3
pool-1-thread-2:0
pool-1-thread-2:1
pool-1-thread-2:2
pool-1-thread-2:3
pool-1-thread-2:4
pool-1-thread-1:4

//Callable:是带泛型的接口。
//这里指定的泛型其实是call()方法的返回值类型。
//返回值类型是Boolean的call

public class MyCallable implements Callable<Boolean> {
    int number;

    public MyCallable(int number) {
        this.number = number;
    }

    public Boolean call() throws Exception {
        if(number%2==0){
            return true;
        }
        return false;
    }
        ExecutorService es=Executors.newFixedThreadPool(2);
        Future<Boolean> a=es.submit(new MyCallable(2));
        Future<Boolean> b=es.submit(new MyCallable(3));
        System.out.println(a.get());
        System.out.println(b.get());
        es.shutdown();
输出:
true
false
posted on 2017-04-07 01:30  2637282556  阅读(99)  评论(0编辑  收藏  举报