生活随笔
收集整理的這篇文章主要介紹了
使用线程池
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
- JDk5.0起提供了線程池相關(guān)的API:ExecutorService和Executors
- ExectorService:真正的線程池接口。常見的子類ThreadPoolExecutor
- void execute(Runnable command):執(zhí)行任務/命令,沒有返回值,一般用來執(zhí)行Runnable
- Futuresubmit(Callabletask):執(zhí)行任務,有返回值,一般用來執(zhí)行Callable
- void shutdown():關(guān)閉線程池
- Executors:工具類,線程池的工具類,用于創(chuàng)并返回不同類型的線程池
package com.zeng.gaoji;
import com.sun.prism.es2.ES2Graphics;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class TestPool {public static void main(String[] args
) {ExecutorService service
= Executors.newFixedThreadPool(10);service
.execute(new MyThread());service
.execute(new MyThread());service
.execute(new MyThread());service
.execute(new MyThread());service
.shutdown();}
}
class MyThread implements Runnable{@Overridepublic void run() {System.out
.println(Thread.currentThread().getName());}
}
package com.zeng.gaoji;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadNew {public static void main(String[] args
) {new MyThread01().start();new Thread(new MyThread02()).start();FutureTask<Integer>futureTask
=new FutureTask<Integer>(new MyThread03());new Thread(futureTask
).start();try {Integer integer
=futureTask
.get();System.out
.println(integer
);} catch (InterruptedException e
) {e
.printStackTrace();} catch (ExecutionException e
) {e
.printStackTrace();}}
}
class MyThread01 extends Thread{@Overridepublic void run() {System.out
.println("MyThread01");}
}
class MyThread02 implements Runnable{@Overridepublic void run() {System.out
.println("MyThread02");}
}
class MyThread03 implements Callable<Integer> {@Overridepublic Integer call()throws Exception{System.out
.println("MyThread03");return 100;}
}
總結(jié)
以上是生活随笔為你收集整理的使用线程池的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。