多線程_線程池的幾種類型


1、線程池一個可以裝入n個線程的容器,每次池子裏面最多能同時運行n個任務(即n個Runnable對象),任務完了,又可以添加新任務,就好像n個線程爲m個任務服務

同時能被服務的任務n個.

2、線程池的種類:

  ①固定線程池:

  ②可緩衝線程池

  ③單線程池:

3、定時器線程池定時器類線程池(在普通線程池上面封裝而來)


               示例如下

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Administrator @zsw 2012-7-20 下午02:31:35
 */
public class ThreadPoolTest {
	public static void main(String[] args) {
		//1、固定線程池:池子裏面只有固定數量的線程
//		ExecutorService threadPool=Executors.newFixedThreadPool(3);
		
		//2、可緩存的線程池:線程池裏面的線程數量根據任務數量動態變化
//		ExecutorService threadPool=Executors.newCachedThreadPool();
		
		/*
		 * 3、單線程池:線程池裏面只有一個線程,與單線程的區別是,
		 * 這個池子裏面的線程死了會自己找一個替補
		 */
		 ExecutorService threadPool=Executors.newSingleThreadExecutor();   
		
		for(int i=1;i<=10;i++){
			final int task=i;
			threadPool.execute(new Runnable(){
				@Override
				public void run() {
					for(int j=1;j<=10;j++){
						System.out.println(Thread.currentThread().getName()+" is loop of "+j+ " for task of "+task);
						/*try {
							Thread.sleep(20);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}*/
					}

				}});
		}
		System.out.println("all of 10 tasks have committed!");
		threadPool.shutdown();//不再添加新任務了,原來的任務幹完,就關掉池子
//		threadPool.shutdownNow();//立刻關閉池子,同時停掉了正在執行的任務
	}

}


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator @zsw 2012-7-20 下午03:34:11
 */
public class ScheduledThreadPoolTest {
	public static void main(String[] args) {
		// 定時器類線程池(在普通線程池上面封裝而來)

		ScheduledExecutorService threadPool = Executors
				.newScheduledThreadPool(3);

		// 1:固定時間後執行一次:5秒後執行一次
		threadPool.schedule(new Runnable() {
			@Override
			public void run() {
				System.out.println("bombing! 一次");

			}
		}, 5, TimeUnit.SECONDS);

		// 2:固定時候後,按照固定頻率不停地執行
		threadPool.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				System.out.println("bombing!不停");

			}
		}, 5, 2, TimeUnit.SECONDS);
		
		threadPool.shutdown();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章