JAVA阻塞线程池

原创
2017/03/18 11:47
阅读数 291

阻塞线程的意义:所有线程执行完毕才返回。

传统线程:所有任务分发完毕即返回。

 

见代码:

package com.test.test;

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

/**
 * 阻塞模式线程池
 * 
 * @author WebSOS
 * @blog http://54sb.org
 *
 */
public class TaskPool {
	ExecutorService exePool;
	private List<Runnable> runnables = new ArrayList<Runnable>();
	private boolean isActivity = true;
	
	private Integer maxThread=100;
	
	private Integer timeOutSeconds=60;
	
	
	public Integer getMaxThread() {
		return maxThread;
	}
	public void setMaxThread(Integer maxThread) {
		this.maxThread = maxThread;
	}
	public TaskPool() {

	}
	public TaskPool(Integer maxThread,Integer timeOutSeconds) {
		this.maxThread=maxThread;
		this.timeOutSeconds=timeOutSeconds;
	}
	public TaskPool(List<Runnable> runnables) {
		this.runnables.addAll(runnables);
	}
	public void execute(List<Runnable> runnables) {
		pushTask(runnables);
		execute();
	}
	public void execute() {
		if (!isActivity) {
			System.out.println("RobotTaskPool:线程池已销毁==================");
		}
		isActivity = false;
		if (runnables==null||runnables.isEmpty()) {
			return;
		}
		Integer currThread = runnables.size();
		if (currThread > maxThread) {
			currThread = maxThread;
		}
		exePool = Executors.newFixedThreadPool(maxThread);
		System.out.println("RobotTaskPool:[" + maxThread + "]执行中==================");
		for (Runnable runnable : runnables) {
			exePool.execute(runnable);
		}
		exePool.shutdown();
		try {
			exePool.awaitTermination(timeOutSeconds, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("RobotTaskPool:[" + maxThread + "]执行完毕==================");
	}

	public boolean pushTask(List<Runnable> runnables) {
		if (!isActivity) {
			System.out.println("RobotTaskPool:线程池已销毁==================");
		}
		this.runnables.addAll(runnables);
		return isActivity;
	}

	public boolean pushTask(Runnable runnable) {
		if (!isActivity) {
			System.out.println("RobotTaskPool:线程池已销毁==================");
		}
		runnables.add(runnable);
		return isActivity;
	}

	public static void main(String[] args) {
	}
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部