Java多線程之Worker Thread模式

一.Worker Thread模式

Worker的意思是工作的人,在Worker Thread模式中,工人線程Worker thread會逐個取回工作並進行處理,當所有工作全部完成後,工人線程會等待新的工作到來。

Worker Thread模式也被成為Background Thread(背景線程)模式,另外,如果從保存多個工人線程的場所這一點看,我們也可以稱這種模式為Thread Pool模式。

二   .Worker Thread模式中的角色

1.Client(委托者)

創建表示工作請求的Request並將其傳遞給Channel。在示例程序中,ClientThread相當於該角色。

2.Channel(通信線路)

Channel角色接受來自於ClientRequest,並將其傳遞給Worker。在示例程序中,Channel相當於該角色。

3.Worker(工人)

Worker角色從Channel中獲取Request,並進行工作,當一項工作完成後,它會繼續去獲取另外的Request,在示例程序中,WorkerThread相當於該角色。

4.Request(請求)

Request角色是表示工作的角色,Request角色中保存瞭進行工作所必須的信息,在示例程序中,Request相當於該角色。

三.Worker Thread使用場景

想象一個場景,一個工廠在生產玩具,在一個車間裡,有幾個工人,每次生產部件準備好車間外的人就將部件放到車間的一個桌子上,工人每次做完一個玩具就從桌子上取部件。在這裡,註意到,部件並不是直接交給工人的,另外一點,工人並不是做完一個部件就回傢換個新人,後者在現實有點滑稽,但是在程序中卻對應一個典型的線程使用方法:線程池。

所謂線程池,就是對線程的復用,當線程執行完任務之後就繼續取其他任務執行,而不是銷毀啟動新線程執行其他任務。因為線程的啟動對於系統性能開銷比較大,所以這樣對於系統性能的提高很有好處。

四.Worker Thread模式程序示例

首先是請求,即玩具的部件

public class Request {

    private final String name;
    private final int number;

    public Request(String name, int number) {
        this.name = name;
        this.number = number;
    }

    public void execute(){
        System.out.println(Thread.currentThread().getName()+" executed "+this);
    }
    @Override
    public String toString() {
        return "Request=> " + "No." + number + "  Name." + name;
    }
}

也就是擁有namenumber並且execute的時候打印出字段的一個簡單類。

ClientThread,負責將請求放入RequestQueue中,即將部件放到桌子上。

public class ClientThread extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());

    private final Channel channel;

    public ClientThread(String name, Channel channel) {
        super(name);
        this.channel = channel;
    }

    @Override
    public void run() {
        try {

            for (int i = 0; true; i++) {
                Request request = new Request(getName(),i);
                this.channel.put(request);
                Thread.sleep(random.nextInt(1_000));
            }
        } catch (Exception e) {

        }
    }
}

Channel類,可以當做車間

public class Channel {

    private final static int MAX_REQUEST = 100;

    private final Request[] requestQueue;
    private final WorkerThread[] workerPool;
    private int head;
    private int tail;
    private int count;

    public Channel(int workers) {

        this.requestQueue = new Request[MAX_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.workerPool = new WorkerThread[workers];
        this.init();
    }

    private void init() {
        for (int i = 0; i < workerPool.length; i++) {
            workerPool[i] = new WorkerThread("Worker-" + i, this);
        }
    }

    /**
     * push switch to start all of worker to work
     */
    public void startWorker() {
        Arrays.asList(workerPool).forEach(WorkerThread::start);

//        List<WorkerThread> workerThreads = Arrays.asList(workerPool);
//
//        workerThreads.stream().forEach(WorkerThread::start);
    }

    public synchronized void put(Request request) {
        while (count >= requestQueue.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.requestQueue[tail] = request;
        this.tail = (tail + 1) % requestQueue.length;
        this.count++;
        this.notifyAll();
    }

    public synchronized Request take() {
        while (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = this.requestQueue[head];
        this.head = (this.head + 1) % this.requestQueue.length;
        this.count--;
        this.notifyAll();
        return request;
    }
}

Requestqueue可以當做桌子,是一個數量有限的請求隊列。threadPool是一個工人線程的數組,這就是一個線程池。在這裡提供瞭putRequesttakeRequest方法,分別是往請求隊列放入請求和取出請,這裡使用瞭上一篇博文講到的生產者消費者模式 java多線程設計模式之消費者生產者模式。確保瞭WorkerThreadClientThread之間可以友好合作。

工人線程:

public class WorkerThread extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());
    private final Channel channel;

    public WorkerThread(String name, Channel channel) {
        super(name);
        this.channel = channel;
    }

    @Override
    public void run() {
        while (true) {
            channel.take().execute();

            try {
                Thread.sleep(random.nextInt(1_000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

這裡就是一個不斷從請求隊列中取出請求然後執行請求的過程,保證瞭工人線程的復用,並不會執行完一個請求任務就銷毀。

最後是Main:

public class WorkerClient {

    public static void main(String[] args) {
        final Channel channel = new Channel(5);
        channel.startWorker();

        new ClientThread("Alex", channel).start();
        new ClientThread("Jack", channel).start();
        new ClientThread("William", channel).start();
    }
}

結果:

Worker-4 executed Request=> No.0  Name.Alex
Worker-2 executed Request=> No.0  Name.Jack
Worker-3 executed Request=> No.0  Name.William
Worker-4 executed Request=> No.1  Name.Jack
Worker-0 executed Request=> No.1  Name.William
Worker-3 executed Request=> No.2  Name.Jack
Worker-2 executed Request=> No.1  Name.Alex
Worker-4 executed Request=> No.2  Name.William
Worker-1 executed Request=> No.3  Name.Jack
Worker-3 executed Request=> No.2  Name.Alex
Worker-4 executed Request=> No.3  Name.William
Worker-0 executed Request=> No.4  Name.Jack
Worker-0 executed Request=> No.3  Name.Alex
Worker-1 executed Request=> No.5  Name.Jack
Worker-3 executed Request=> No.4  Name.William
Worker-1 executed Request=> No.6  Name.Jack
Worker-2 executed Request=> No.4  Name.Alex
Worker-3 executed Request=> No.7  Name.Jack
Worker-0 executed Request=> No.5  Name.William
Worker-1 executed Request=> No.5  Name.Alex
Worker-4 executed Request=> No.8  Name.Jack
Worker-2 executed Request=> No.6  Name.Alex
Worker-0 executed Request=> No.7  Name.Alex
Worker-4 executed Request=> No.8  Name.Alex
Worker-2 executed Request=> No.6  Name.William
省略…

可以看出線程執行任務的線程就是WorkerThread1,2,3,4,5五個,它們不斷執行來自ClientThread Alex,Jack,William的請求任務。

到此這篇關於Java多線程之Worker Thread模式的文章就介紹到這瞭,更多相關Java多線程 Worker Thread內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: