java 线程池的用法

1.java自带的类ExecutorService用于提供线程池服务,可以一下方法初始化线程池:

 ExecutorService pool = Executors.newFixedThreadPool(5);//固定线程的线程池
 ExecutorService pool = Executors.newCachedThreadPool();//具有伸缩的线程池

使用一下代码:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPool {
    public static void main(String[] args) throws  Exception{
        ExecutorService pool = Executors.newFixedThreadPool(4);
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.shutdown();
    }

}
public class MyThread extends  Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在执行...");
    }
}

执行结果为:

pool-1-thread-1正在执行...
pool-1-thread-3正在执行...
pool-1-thread-4正在执行...
pool-1-thread-2正在执行...

若将线程池的大小改为3(比我们定义的线程数量要小):

运行结果为:

pool-1-thread-1正在执行...
pool-1-thread-2正在执行...
pool-1-thread-3正在执行...
pool-1-thread-1正在执行...

从以上结果可以看出,newFixedThreadPool的参数指定了可以运行的线程的最大数目,超过这个数目的线程加进去以后,不会运行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。当然使用newCachedThreadPool就不会出现这个问题。

现在我们定义:

import java.util.concurrent.Callable;
public
class MyList implements Callable<List<String>>{ static int i =1; @Override public List call() throws Exception { List list = new ArrayList(); list.add("------------------1"); list.add("------------------2"); list.add("------------------3"); System.out.println("---i=:"+i++); return list; } }

ThreadPool的main方法中:

  List<MyList> list = new ArrayList();
  MyList myf = new MyList();
  list.add(myf);
  list.add(myf);
  List<Future<List<String>>>  futureList = pool.invokeAll(list);
  System.out.println("----:"+  futureList.size());

自定义的MyList 实现了接口Callable的call()方法。

pool.invokeAll(list)将使用线程去执行list对象中的call()方法,然后见执行的结构返回到集合中( List<Future<返回类型>>中的类型要与实现接口Callable<返回类型>中的类型一致)。

上面程序执行的结果为:

---i=:1
---i=:2
----:2

  

原文地址:https://www.cnblogs.com/mouseIT/p/5016616.html