1. 程式人生 > 實用技巧 >一個執行緒執行多個任務,按照順序執行

一個執行緒執行多個任務,按照順序執行

一個執行緒執行多個任務,要按照順序執行,怎麼去實現?

分析:

多個人任務-->執行緒
要按照順序執行--》就需要排隊,那就是佇列
一個給任務,一個執行任務--》涉及一個生產一個消費
過渡:需要容器裝任務來儲存任務
有兩個執行緒,一放一取不是原子操作,所以涉及執行緒安全問題

程式碼實現:

import java.util.concurrent.ArrayBlockingQueue;
public class TestIOBlocking {
	static int m=0;
	//主執行緒
	public static void main(String[] args) {
		System.out.println("開始!");
		//生產任務的
		TestExecutor t=new TestExecutor();
		for(int i=0;i<20;i++) {
			t.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println("test"+TestIOBlocking.m++);
				}
			});	
		}
		
	} 
}
class TestExecutor{
	public TestExecutor() {
		//建立物件就執行
		thread.start();
	}
	private static workThread thread=new workThread();
	//儲存任務的容器,先設定存3個任務,這是一個阻塞的佇列
	private static ArrayBlockingQueue<Runnable> queue=new ArrayBlockingQueue<Runnable>(3);
	
	//工作執行緒
	static class workThread extends Thread{
		@Override
		public void run() {
				//執行的任務,反覆的取
			while(TestIOBlocking.m<=19) {
				try {
					Runnable r=queue.take();//阻塞方法
					r.run();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	//取任務的方法
	public void execute(Runnable r) {
		try {
			queue.put(r);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

擴充套件:

  1. 怎麼實現一個阻塞式對列結構?
  2. 怎麼實現一個LruCache快取結構(不依託於LikedList,HashMap來實現)?
    (lru:最近最少演算法)