import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.*;
class HelloWorld {
static class Worker extends Thread {
BlockingQueue queue = null;
int id=0;
public Worker(BlockingQueue queue, int id) {
this.queue = queue;
this.id=id;
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Runnable runnable = queue.take();
System.out.println("线程" + id + "正在执行");
runnable.run();
} catch(InterruptedException e){
e.printStackTrace();
System.out.println("线程结束");
break;
}}
}
}
static class mypool {
private BlockingQueue queue = new linkedBlockingQueue();
ArrayList arrayList = new ArrayList<>();
public void excute(Runnable command) throws InterruptedException {
queue.put(command);
if (arrayList.size() < 3) {
Worker x = new Worker(queue,arrayList.size());
x.start();
arrayList.add(x);
}
}
public void shutdown()throws InterruptedException
{
for(Worker worker:arrayList)
{
worker.interrupt();
}
for(Worker worker:arrayList)
{
worker.join();
}
}
}
static class Command implements Runnable
{ int num;
public Command(int num)
{
this.num=num;
}
public void run()
{
System.out.println("线程"+num+"正在工作");
}
}
public static void main(String[] args) throws InterruptedException{
mypool o=new mypool();
for(int i=0;i<100;i++)
{
o.excute(new Command(i));
}
try {
Thread.sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
o.shutdown();
System.out.println("线程池已销毁");
}
}