package com.huawei.thread;
import java.util.LinkedList;
public class WorkQueue extends Thread
{
private final int nThreads;//线程池的大小
private final PoolWorker[] threads;//用数组实现线程池
private final LinkedList queue;//任务队列
public void run()
{
while (true)
{
int i = 0;
for (i = 0; i < nThreads; i++)
{
if (threads[i].getWorking() == true)
{
break;
}
}
//System.out.println("i ========" + i);
if (i == nThreads)
{
System.exit(-1);
}
}
}
public WorkQueue(int nThreads)
{
this.nThreads = nThreads;
queue = new LinkedList();
threads = new PoolWorker[nThreads];
for (int i = 0; i < nThreads; i++)
{
threads[i] = new PoolWorker(i);
try
{
threads[i].start();
} catch (Exception e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}//启动所有工作线程
}
}
public void execute(Mytask r)
{//执行任务
synchronized (queue)
{
queue.addLast(r);
System.out.println("当前队列任务数"+queue.size());
queue.notify();
}
}
class PoolWorker extends Thread
{
private boolean isWroking = true;
private int num;
PoolWorker(int num)
{
this.num = num;
System.out.println("线程"+num+"启动...");
}
boolean getWorking()
{
return isWroking;
}
//工作线程类
public void run()
{
Mytask r;
while (true)
{
synchronized (queue)
{
while (queue.isEmpty())
{
isWroking = false;
System.out.println("线程"+num+"没有任务,线程等待...........");
//如果任务队列中没有任务,等待
try
{
queue.wait();
} catch (InterruptedException ignored)
{
}
}
isWroking = true;
r = (Mytask) queue.removeFirst();//有任务时,取出任务
}
try
{
System.out.println("线程"+num+"正在处理"+((Mytask)r).getTasknum());
r.runTask();//执行任务
System.out.println("线程"+num+"处理完毕 "+((Mytask)r).getTasknum());
} catch (RuntimeException e)
{
// You might want to log something here
}
}
}
}
public static void main(String args[])
{
WorkQueue wq = new WorkQueue(10);//10个工作线程
Mytask r[] = new Mytask[20];//20个任务
for (int i = 0; i < 20; i++)
{
r[i] = new Mytask(i);
wq.execute(r[i]);
}
try
{
wq.run();
} catch (Exception e)
{
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
class Mytask //implements Runnable
{//任务接口
private int tasknum;
Mytask(int num)
{
this.tasknum = num;
}
public int getTasknum()
{
return tasknum;
}
public void runTask(){
String name=Thread.currentThread().getName();
try{
Thread.sleep(2000);//模拟任务执行的时间
}catch(InterruptedException e){}
//System.out.println("任务"+name+" executed OK");
}
}