package maptoxml;
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) {
super(name);
}
Runnable task;
public void run() {
System.out.println("启动: " + this.getName());
while (true) {
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
task = tasks.removeLast();
// 允许添加任务的线程可以继续添加任务
tasks.notifyAll();
}
System.out.println(this.getName() + " 获取到任务,并执行");
task.run();
}
}
}
}
package maptoxml;
public class TestThread {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool();
for (int i = 0; i < 5; i++) {
Runnable task = new Runnable() {
@Override
public void run() {
//System.out.println("执行任务");
//任务可能是打印一句话
//可能是访问文件
//可能是做排序
}
};
pool.add(task);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
创造一个情景,每个任务执行的时间都是1秒
刚开始是间隔1秒钟向线程池中添加任务
然后间隔时间越来越短,执行任务的线程还没有来得及结束,新的任务又来了。
就会观察到线程池里的其他线程被唤醒来执行这些任务
package maptoxml;
public class TestThread {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool();
int sleep = 1000;
for (int i = 0; i < 5; i++) {
Runnable task = new Runnable() {
@Override
public void run() {
//System.out.println("执行任务");
//任务可能是打印一句话
//可能是访问文件
//可能是做排序
}
};
pool.add(task);
try {
Thread.sleep(sleep);
sleep = sleep>100?sleep-100:sleep;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}