package
com.zhf.android_frameworkdemo03.threadpool;
import
java.util.Collections;
import
java.util.LinkedList;
import
java.util.List;
import
android.util.Log;
/**
* 线程池管理器
* @author ZHF
*
*/
public
class
ThreadPoolManager {
public
static
String TAG =
"ThreadPoolManager"
;
public
static
ThreadPoolManager instance =
null
;
public
static
List<Task> taskQueue = Collections.synchronizedList(
new
LinkedList());
private
WorkThread[] workQueue;
private
static
int
threadNumber =
5
;
/**构造方法(单例)**/
private
ThreadPoolManager(TaskOperate taskOperate) {
this
(threadNumber, taskOperate);
}
/**构造方法(单例):实例化线程数组**/
private
ThreadPoolManager(
int
threadNumber, TaskOperate taskOperate) {
this
.threadNumber = threadNumber;
this
.workQueue =
new
WorkThread[threadNumber];
for
(
int
i =
0
; i < threadNumber; i++) {
this
.workQueue[i] =
new
WorkThread(i, taskOperate);
System.out.println(
"当前运行的是"
+ i +
"个线程"
);
}
}
/**获取该类的实例对象(懒汉式)**/
public
static
synchronized
ThreadPoolManager getInstance(TaskOperate taskOperate) {
if
(instance ==
null
) {
instance =
new
ThreadPoolManager(taskOperate);
return
instance;
}
return
null
;
}
/**添加单个任务**/
public
void
addTask(Task task) {
synchronized
(taskQueue) {
if
(task !=
null
) {
taskQueue.add(task);
taskQueue.notifyAll();
System.out.println(
"任务: "
+ task.getTaskInfo() +
"--添加成功--"
);
}
}
}
/**添加多个任务**/
public
void
addTasks(Task[] tasks) {
synchronized
(taskQueue) {
for
(Task t : tasks) {
if
(tasks !=
null
) {
taskQueue.add(t);
taskQueue.notifyAll();
System.out.println(
"任务: "
+ t.getTaskInfo() +
"--添加成功--"
);
}
}
}
}
/**销毁线程**/
public
void
destroy() {
Log.i(TAG,
"线程池管理器destroy方法开始。。。"
);
for
(
int
i =
0
; i < threadNumber; i++) {
this
.workQueue[i].stopThread();
this
.workQueue[i] =
null
;
}
synchronized
(taskQueue) {
taskQueue.clear();
}
Log.i(TAG,
"线程池管理器destroy方法结束。。。"
);
System.gc();
}
}