Java四種執行緒池的使用
阿新 • • 發佈:2019-01-29
http://cuisuqiang.iteye.com/blog/2019372
http://www.cnblogs.com/riskyer/p/3263032.html
http://blog.csdn.net/mazhimazh/article/details/19243889
Java通過Executors提供四種執行緒池,newCacheThreadPool(),newFixedThreadPool(),newScheduedThreadPool(),newSingleThreadPool()
newCacheThreadPool(), 建立一個可快取的執行緒池,如果執行緒池長度超過處理需要,可靈活回收空閒執行緒,如果執行緒池長度小於處理需求,則新建執行緒這種執行緒池在一下加入多個任務的時候,長度會變得很大,會一直新建執行緒,當沒有任務時,空閒執行緒會被回收<span style="font-family:KaiTi_GB2312;font-size:12px;">public class Main { public static void main( String[] args ) { ExecutorService executors = Executors.newCachedThreadPool(); SleepTread mSleepTread; for ( int i = 0 ; i < 30 ; i++ ) { mSleepTread = new SleepTread(); executors.execute(mSleepTread); } executors.shutdown(); } static class SleepTread extends Thread { @Override public void run() { super.run(); try { Thread.sleep(1500); } catch ( InterruptedException e ) { e.printStackTrace(); } System.out.println(this.getName() + " ----- "); } } }</span>
newFixedThreadPool
<span style="font-family:KaiTi_GB2312;font-size:12px;">public static void main( String[] args ) {
ExecutorService executors = Executors.newFixedThreadPool(3);
SleepTread mSleepTread;
for ( int i = 0 ; i < 30 ; i++ ) {
mSleepTread = new SleepTread();
executors.execute(mSleepTread);
}
executors.shutdown();
}</span>
這個執行緒固定長度,
newScheduledThreadPool
<span style="font-family:KaiTi_GB2312;font-size:12px;"> public static void main( String[] args ) {
ScheduledExecutorService executors = Executors.newScheduledThreadPool(5);
SleepTread mSleepTread;
for ( int i = 0 ; i < 30 ; i++ ) {
mSleepTread = new SleepTread();
// executors.execute(mSleepTread);
//延遲多上時間執行,時間單位
executors.schedule(mSleepTread, 3, TimeUnit.SECONDS);
}
executors.shutdown();
}</span>
定時,或者迴圈執行的執行緒池,可定時,並不是execute執行,如果execute執行就沒有效果延遲效果,對應還有兩個方法,scheduleAtFixedRate(),和ScheduleWithFixedDelay(),第二個引數為任務執行完之後間隔下一個任務的停頓時間,第三個引數為最開始沒執行任務時的等待時間newSingleThreadExecutor
<span style="font-family:KaiTi_GB2312;font-size:12px;">public static void main( String[] args ) {
ExecutorService executors = Executors.newSingleThreadExecutor();
SleepTread mSleepTread;
for ( int i = 0 ; i < 30 ; i++ ) {
mSleepTread = new SleepTread();
executors.execute(mSleepTread);
}
executors.shutdown();
}</span>
單例模式的執行緒池,同事只有一個任務在執行.還有單例可延遲的執行緒池ScheduleExecutorService
<span style="font-family:KaiTi_GB2312;font-size:12px;"> public static void main( String[] args ) {
ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
SleepTread mSleepTread;
for ( int i = 0 ; i < 30 ; i++ ) {
mSleepTread = new SleepTread();
// executors.execute(mSleepTread);
executors.schedule(mSleepTread, 3, TimeUnit.SECONDS);
}
executors.shutdown();
}</span>