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();
}
}
}
}