JAVA多线程设计模式篇 9、Woker Thread 模式——闲时摸鱼、忙时干活

文章目录

在Thread-Per-Message模式中每个工作任务都会启动一个新的线程,为每个或者每一批任务创建一个线程以对其进行执行,通常是一种奢侈而不现实的事情。

而在Worker Thread 模式中,工人线程会反复进行工作,无需启动新线程。比较常见的一种做法是复用一定数量的线程,由这些线程去执行不断执行产生的任务。

绝大多数的Web服务器就是采用这种方法。例如,Tomcat服务器复用一定数量的线程用于处理其接收到的请求。Worker Thread 模式的核心思想是使用队列对待处理的任务进行缓存,并复用一定数量的工作者线程去取队列中的任务进行执行。

1.优点

  • 抵消线程创建的开销,提高响应性。
  • 封装了工作者线程生命周期管理。
  • 减少销毁线程的开销。

2.示例

如下代码,Channel类存储任务,使用了生产者-消费者模式。

WorkerThread[] threadsPool 是线程池,使用的是Worker Thread模式,也称为线程池模式。

//Worker线程池
public class Channel {
    private static final int MAX_REQUEST=100;
    private final Request[] requestQueue;
    private int tail;
    private int head;
    private int count;
    private final WorkerThread[] threadsPool;
    public Channel(int threads){
        this.requestQueue=new Request[MAX_REQUEST];
        this.head=0;
        this.tail=0;
        this.count=0;
        threadsPool=new WorkerThread[threads];
        for(int i=0;i<threadsPool.length;i++){
            threadsPool[i]=new WorkerThread("Worker-"+i,this);
        }
    }
    public void startWorkers(){
        for(int i=0;i<threadsPool.length;i++){
            threadsPool[i].start();
        }
    }
    public synchronized void  putRequest(Request request){
        while(count>=requestQueue.length){
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        requestQueue[tail]=request;
        tail=(tail+1)%requestQueue.length;
        count++;
        notifyAll();
    }
    public synchronized Request takeRequest(){
        while(count<=0){
            try{
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        Request request=requestQueue[head];
        head=(head+1)%requestQueue.length;
        count--;
        notifyAll();
        return request;
    }
}
//客户线程,发送请求
public class ClientThread extends Thread{
    private final Channel channel;
    private static final Random random=new  Random();
    public ClientThread(String name,Channel channel){
        super(name);
        this.channel=channel;
    }
    public void run(){
        try{
            for(int i=0;true;i++){
                Request request=new Request(getName(),i);
                channel.putRequest(request);
                Thread.sleep(random.nextInt(1000));
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
}
//工人线程,处理请求
public class WorkerThread extends Thread{
    private final Channel channel;
    public WorkerThread(String name,Channel channel){
        super(name);
        this.channel=channel;

    }
    public void run(){
        while(true){
            Request request=channel.takeRequest();
            request.execute();
        }
    }
}
//模拟请求
public class Request {
    private final String name;
    private final int number;
    private static final Random random=new Random();
    public Request (String name,int number){
        this.name=name;
        this.number=number;
    }
    public void execute(){
        System.out.println(Thread.currentThread().getName()+" executes "+this);
        try{
            Thread.sleep(random.nextInt(1000));
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    @Override
    public String toString(){
        return "[Request from "+name+" NO."+number+"]";
    }
}
//启动类
public class Tester {
    public static void main(String[] args){
        Channel channel=new Channel(5);
        channel.startWorkers();
        new ClientThread("Alice",channel).start();
        new ClientThread("Bobby",channel).start();
        new ClientThread("Chris",channel).start();
    }
}

总结

java.util.concurrent.ThreadPoolExecutor就是Worker Thread 模式的一个实现。

多线程系列在github上有一个开源项目,主要是本系列博客的实验代码。

https://github.com/forestnlp/concurrentlab

如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。

您的支持是对我最大的鼓励。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟空学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值