创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
newScheduledThreadPool
public class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行。。。");
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestSingleThreadExecutor{
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
//将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
//在确定没有线程要执行的时候关闭线程池
pool.shutdown();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestSingleThreadExecutor {
private int port = 8000;
private ServerSocket serverSocket;
private ExecutorService executorService;//线程池
private int poolSize = 4;//单个cpu时线程池中工作线程的数目
public void service() throws IOException{
serverSocket = new ServerSocket(port);
//创建线程池,大小为CPU数*poolSize
executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()*poolSize);
while(true){
Socket socket = null;
socket = serverSocket.accept();
//把线程加到线程池中
executorService.execute(new HandlerThread(socket));
}
}
}
class HandlerThread implements Runnable{
private Socket socket;
public HandlerThread (Socket socket){
this.socket = socket;
}
public void run(){
try{
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
String msg = null;
while((msg=br.readLine())!=null){
System.out.println(msg);
pw.println("echo:"+msg);
if(msg.equals("bye"))
break;
}
if(socket!=null){
socket.close();
}
}catch(IOException e){}
}
}
public class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行。。。");
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCachedThreadExecutor{
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
Thread t1 = new MyThread();
Thread t2 = new MyThread();
Thread t3 = new MyThread();
//将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
//在确定没有线程要执行的时候关闭线程池,如果后面可能还有线程要执行,不要关闭
pool.shutdown();
}
}
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestScheduledThreadPoolExecutor{
public static void main(String[] args) {
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(new HandleThread("NO.1"), 1000, 5000, TimeUnit.MILLISECONDS);
exec.scheduleAtFixedRate(new HandleThread("NO.2"), 1000, 2000, TimeUnit.MILLISECONDS);
//......
}
}
class HandleThread implements Runnable{
String name = "";
public HandleThread(String name) {
this.name = name;
}
public void run(){
System.out.println(name);
}
}
上面是JDK提供线程池的实现,如果想自己实现线程池,可以用下面方法:
public class ThreadPoolTester {
public static void main(String[]args){
int numTasks = 30;//任务数目
int poolSize = 4;//线程池中的线程数目
ThreadPool threadPool = new ThreadPool(poolSize);
for(int i = 0;i<numTasks;i++){
threadPool.execute(creatTask(i));
}
threadPool.join();
threadPool.close();
}
private static Runnable creatTask(final int taskID){
return new Runnable() {
public void run() {
/*
* 这里是线程要执行的一些操作,可以是while循环
*/
System.out.println("Task"+taskID+":start");
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
System.out.println("Task"+taskID+":end");
}
};
}
}
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup{
private boolean isClosed = false;//线程池是否关闭
private LinkedList<Runnable> workQueue;//工作队列
private int threadID;//工作线程ID
private static int threadPoolID;//线程池ID
public ThreadPool(int poolSize){
super("ThreadPool-"+(threadPoolID++));
setDaemon(true);
workQueue = new LinkedList<Runnable>();
for(int i=0;i<poolSize;i++){
new WorkThread().start();
}
}
/*
*内部类:工作线程
*/
private class WorkThread extends Thread{
public WorkThread(){
//加入当前线程池
super(ThreadPool.this,"WorkThread-"+(threadID));
}
public void run(){
while(!isInterrupted()){
/*
* isInterrupted()方法继承自Thread类,判断线程是否被中断.
* 由于该线程加入了线程池,所以线程池可以调用方法对其中断
*/
Runnable task = null;
try{
task = getTask();
}catch (InterruptedException e) {}
if(task==null)return;
try {
task.run();
} catch (Throwable t) {}
}
}
}
protected synchronized Runnable getTask() throws InterruptedException {
while(workQueue.size()==0){
if(isClosed)return null;
wait();
}
return workQueue.removeFirst();
}
//向工作队列加入一个新任务
public synchronized void execute(Runnable task){
if(isClosed){
throw new IllegalStateException();
}
if(task!=null){
workQueue.add(task);
notify();//唤醒正在getTask()方法中等待任务的工作线程
}
}
/*
* 等待工作线程把所有任务都执行完
*/
public void join(){
synchronized (this) {
isClosed = true;
/*
* 唤醒还在getTask()方法中等待任务的工作线程
* 因为如果不唤醒,这些线程结束不了
* 由于isClosed被设为true,唤醒之后,这些线程可以返回
*/
notifyAll();
}
Thread[]threads = new Thread[activeCount()];
//enumerate()方法继承自ThreadGroup类,获得线程组中所有活着的工作线程
int count = enumerate(threads);
for(int i=0;i<count;i++){
try {
/*
*等到线程i结束才往下执行,for循环之后所有的活动
*线程都已结束
*/
threads[i].join();
} catch (InterruptedException e) {}
}
}
public synchronized void close(){
if(!isClosed){
isClosed = true;
workQueue.clear();
interrupt();//中断所有工作线程,继承自ThreadGroup类
}
}
}