1、线程池
package com.oyhp.thread;
import java.util.LinkedList;
public class ThreadPool {
//线程大小
int threadPoolSize;
//任务容器
LinkedList<Runnable> tasks = new LinkedList<Runnable>();
//试图消费任务的线程
public ThreadPool(){
threadPoolSize = 10;
//启动10个任务消费级线程
synchronized (tasks) {
for (int i = 0; i < threadPoolSize; i++) {
new TaskConsumeThread("任务消费线程" + i + "-启动").start();
}
}
}
public void add(Runnable r){
synchronized (tasks) {
tasks.add(r);
// 唤醒等待的任务消费者线程
tasks.notifyAll();
}
}
class TaskConsumeThread extends Thread{
public TaskConsumeThread(String name) {
// TODO Auto-generated constructor stub
super(name);
}
Runnable task;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("启动: " + this.getName());
while(true){
synchronized (tasks) {
while(tasks.isEmpty()){
try {
System.out.println(this.getName() + "正在等待");
tasks.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
task = tasks.removeLast();
// 允许添加任务的线程可以继续添加任务
tasks.notifyAll();
}
System.out.println(this.getName() + "获取到任务并执行");
task.run();
}
}
}
}
2、测试线程池
package com.oyhp.thread;
public class TestThread {
public static void main(String[] args) {
ThreadPool pool= new ThreadPool();
int sleep=1000;
while(true){
pool.add(new Runnable(){
@Override
public void run() {
//System.out.println("执行任务");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
try {
Thread.sleep(sleep);
sleep = sleep>100?sleep-100:sleep;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}