四種常見線程池使用舉例


線程池

線程池:Executor 管理多個異步任務的執行,而無需程序員顯式地管理線程的生命周期。這里的異步是指多個任務的執行互不干擾,不需要進行同步操作。

主要有四種線程池:

緩存池

newCachedThreadPool創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。

下面是它的使用方法:

package com.xzj;

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

//   @ author :zjxu     time:2019/1/5
public class Main {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            cachedThreadPool.execute(new MyRunnable());
        }
        cachedThreadPool.shutdown();
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println(new Date().toString());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

定長池

newFixedThreadPool可以創建一個定長的線程池。定長線程池最多只能同時執行一定個數的線程,這個容量在new的時候設定。

下面是一個示例:

package com.xzj;

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

//   @ author :zjxu     time:2019/1/5
public class Main {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            cachedThreadPool.execute(new MyRunnable());
        }
        cachedThreadPool.shutdown();
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println(new Date().toString());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

 

運行結果:
Sat Jan 05 11:59:13 CST 2019
Sat Jan 05 11:59:13 CST 2019
Sat Jan 05 11:59:13 CST 2019
Sat Jan 05 11:59:15 CST 2019
Sat Jan 05 11:59:15 CST 2019
Sat Jan 05 11:59:15 CST 2019
Sat Jan 05 11:59:17 CST 2019
Sat Jan 05 11:59:17 CST 2019
Sat Jan 05 11:59:17 CST 2019
Sat Jan 05 11:59:19 CST 2019

 

 

 

定時池

newScheduledThreadPool創建一個定長線程池,支持延遲執行和周期性任務執行。后一種執行方式類似於單片機的定時器中斷。

1、延遲執行

package com.xzj;

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

//   @ author :zjxu     time:2019/1/5
public class Main {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        System.out.println(new Date().toString());
        scheduledThreadPool.schedule(new MyRunnable(), 3, TimeUnit.SECONDS);
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println(new Date().toString());
    }
}

 

 

結果:

SatJan0512:15:35CST2019
SatJan0512:15:38CST2019

 

1、周期執行

scheduleAtFixedRate(x,x,x,x)的第二個參數的意義是初始化延遲,第三個參數的意義是定時間隔延遲。

package com.xzj;

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

//   @ author :zjxu     time:2019/1/5
public class Main {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        System.out.println(new Date().toString());
        scheduledThreadPool.scheduleAtFixedRate(new MyRunnable(), 1, 3, TimeUnit.SECONDS);
        try {
            Thread.sleep(15 * 1000);
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        scheduledThreadPool.shutdown();
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println(new Date().toString());
    }
}

 

 

運行的結果

1 Sat Jan 05 12:21:07 CST 2019
2 Sat Jan 05 12:21:08 CST 2019
3 Sat Jan 05 12:21:11 CST 2019
4 Sat Jan 05 12:21:14 CST 2019
5 Sat Jan 05 12:21:17 CST 2019
6 Sat Jan 05 12:21:20 CST 2019

 結果中第一二行的原因就是初始化延遲參數形成的。

 

單線程線程池

newSingleThreadExecutor創建一個單線程化的線程池,這個線程池當前池中的線程死后(或發生異常時),才能重新啟動新的一個線程來替代原來的線程繼續執行下去。也就是說按照單線程的模式,會按照線程添加的順序,一個一個的執行這些線程的工作。

package com.xzj;

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

//   @ author :zjxu     time:2019/1/5
public class Main {
    public static void main(String[] args) {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(new MyRunnable(index));
        }
    }
}

class MyRunnable implements Runnable {
    int i = 0;

    public MyRunnable(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        try {
            System.out.print(i+" ");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

運行的結果
0 1 2 3 4 5 6 7 8 9 

 

按照順序,一個一個一次執行。

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM