方法实现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++);
}
}