此方法實現java多線程順序執行,依賴的是LinkedList < Runnable > ,因爲鏈表裏的元素是有序的,先放進去的先出來,所以最先進去的CreateTaskByThread最先出來. 其次consumptionThread 線程監聽tasks裏面放進去的任務,類似於消費者,如果有任務的話會立即執行,消費掉tasks裏面的任務;productionThread 線程負責向LinkedList 鏈表裏增加任務(每隔2s增加一個任務),這樣呢就簡單模仿了一個多線程順序執行的一個案例
import java.util.LinkedList;
public class MultithreadedOrder {
//鏈表
private volatile static LinkedList<Runnable> tasks = new LinkedList<Runnable>();
public static void main(String[] args){
//開始執行,輸出,現在鏈表裏插入10個 runnable 執行
System.out.println("start");
for (int i = 0; i < 10; i++) {
excuteTime();
}
System.out.println("end");
//消費者 執行鏈表裏的任務,消耗鏈表裏的任務
Thread consumptionThread = new Thread(){
@Override
public void run(){
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
if (!tasks.isEmpty()) {
final Runnable task;
synchronized (tasks) {
task = tasks.getFirst();
}
try {
System.out.println("LinkedList-tasks size:"+tasks.size());
task.run();
} catch (Exception ex) {
//throw ex;
System.out.println(ex);
} finally {
synchronized (tasks) {
tasks.removeFirst();
}
}
}
}
}
};
consumptionThread.start();
//生產者 負責向鏈表裏面添加 runnable
Thread productionThread = new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CreateTaskByThread createTaskByThread = new CreateTaskByThread();
tasks.add(createTaskByThread);
}
}
};
productionThread.start();
}
public static void excuteTime(){
CreateTaskByThread createTaskByThread = new CreateTaskByThread();
tasks.add(createTaskByThread);
}
}
class CreateTaskByThread implements Runnable{
private static int i = 0;
@Override
public void run() {
System.out.println("best_"+ i++);
}
}