线程池
线程池
线程池事先准备好一定数目的线程,需要使用时把线程当作载体,直接拿出来用,无需再创建。
以下代码演示如何在java中使用线程池:
package com.cxf.multithread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestForPool {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new Myjob());
service.execute(new Myjob());
service.execute(new Myjob());
service.execute(new Myjob());
service.shutdown();
}
}
class Myjob implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
输出结果:
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-2 is running
pool-1-thread-3 is running
java中通过newFixedThreadPool方法来实现线程池,创建线程池相当于创建一个服务。
用execute运行线程相当于开启服务,线程结束后需要用shutdown关闭服务。