packagecom.smart.frame.task.autoTask;importjava.util.Collection;importjava.util.Vector;/*** 任务分发器*/
public class TaskManage extendsThread
{protected Vector tasks = new Vector();protected boolean running = false;protected boolean stopped = false;protected boolean paused = false;protected boolean killed = false;privateThreadPool pool;publicTaskManage(ThreadPool pool)
{this.pool =pool;
}public voidputTask(Runnable task)
{
tasks.add(task);
}public voidputTasks(Runnable[] tasks)
{for (int i = 0; i < tasks.length; i++)this.tasks.add(tasks[i]);
}public void putTasks(Collectiontasks)
{this.tasks.addAll(tasks);
}protectedRunnable popTask()
{if (tasks.size() > 0) return (Runnable) tasks.remove(0);else return null;
}public booleanisRunning()
{returnrunning;
}public voidstopTasks()
{
stopped= true;
}public voidstopTasksSync()
{
stopTasks();while(isRunning())
{try{
sleep(5);
}catch(InterruptedException e)
{
TaskException.getResultMessage(e);
}
}
}public voidpauseTasks()
{
paused= true;
}public voidpauseTasksSync()
{
pauseTasks();while(isRunning())
{try{
sleep(5);
}catch(InterruptedException e)
{
TaskException.getResultMessage(e);
}
}
}public voidkill()
{if (!running) interrupt();else killed = true;
}public voidkillSync()
{
kill();while(isAlive())
{try{
sleep(5);
}catch(InterruptedException e)
{
TaskException.getResultMessage(e);
}
}
}public synchronized voidstartTasks()
{
running= true;this.notify();
}public synchronized voidrun()
{try{while (true)
{if (!running || tasks.size() == 0)
{
pool.notifyForIdleThread();this.wait();
}else{
Runnable task;while ((task = popTask()) != null)
{
task.run();if(stopped)
{
stopped= false;if (tasks.size() > 0)
{
tasks.clear();
System.out.println(Thread.currentThread().getId()+ ": Tasks are stopped");break;
}
}if(paused)
{
paused= false;if (tasks.size() > 0)
{
System.out.println(Thread.currentThread().getId()+ ": Tasks are paused");break;
}
}
}
running= false;
}if(killed)
{
killed= false;break;
}
}
}catch(InterruptedException e)
{
TaskException.getResultMessage(e);return;
}
}
}