Thread使用線程池

使用線程池,將實現Runnable接口類的對象作爲參數

Executors:線程池創建工廠類

public static ExecutorService newFixedThreadPool(int nThreads):返回線程池對象

ExecutorService:線程池類

Future<?> submit(Runnable task):獲取線程池中的某一個線程對象,並執行

@Test
	public void test04() {
		//創建線程池
		ExecutorService service = Executors.newFixedThreadPool(2);
		MyThreadCreate02 myThread = new MyThreadCreate02();
		
		//從線程池中獲取線程對象,然後調用MyThreadCreate02中的run()方法
		service.submit(myThread);
		//每調用一次就獲取一個線程
		service.submit(myThread);
		
		//關閉線程池
		service.shutdown();
	}

使用線程池,將實現Callable接口類的對象作爲參數

Callable接口:與Runnable接口功能相似,用來指定線程的任務。其中的call()方法, 用來返回線程任務執行完畢後的結果,call方法可拋出異常

public class MyCallable implements Callable{

	@Override
	public Object call() throws Exception {
		for(int i = 0;i<50;i++) {
			System.out.println("實現Callable接口"+i);
		}
		return null;
	}
}
@Test
	public void test05() {
		//創建線程池
		ExecutorService service = Executors.newFixedThreadPool(2);
		MyCallable callable = new MyCallable();
		//從線程池中獲取線程
		service.submit(callable);
		//關閉線程池
		service.shutdown();
	}

 

 

 

 

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