欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java多线程之Worker Thread模式

程序员文章站 2022-06-16 23:50:56
目录一.worker thread模式二 .worker thread模式中的角色1.client(委托者)2.channel(通信线路)3.worker(工人)4.request(请求)三.work...

一.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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!