当前位置: 首页 > news >正文

worker模式 多线程实现

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

今天来学学,大家也好对线程池有一个更好的理解。

public class Main {  

    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();  

    }  

}  

 

发送请求的client代码:

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 {  

            int i = 0;  

            Request request = new Request(getName(), i);//生成请求   

            channel.putRequest(request);//向队列中放入请求,也即把请求传给线程池   

            Thread.sleep(random.nextInt(1000));  

        } catch (InterruptedException e) {  

        }  

    }  

}  

 

ClientThread建立请求,并把请求传给了channel,下面来看看channel类(相当于线程池类)

public class Channel {  

    private static final int MAX_REQUEST = 100;  

    private final Request[] requestQueue;//存放请求的队列   

    private int tail;  // 下一个putRequest的地方  

    private int head;  // 下一个takeRequest的地方  

    private int count; // Request的数量   

      private final WorkerThread[] threadPool;  

      public Channel(int threads) {  

        this.requestQueue = new Request[MAX_REQUEST];  

        this.head = 0;  

        this.tail = 0;  

        this.count = 0;  

          threadPool = new WorkerThread[threads];  

        for (int i = 0; i < threadPool.length; i++) {  

            threadPool[i] = new WorkerThread("Worker-" + i, this);//生成线程池中的线程   

        }  

    }  

    public void startWorkers() {  

        for (int i = 0; i < threadPool.length; i++) {  

            threadPool[i].start();//启动线程池中的线程   

        }  

    }  

    public synchronized void putRequest(Request request) {//向队列中存入请求   

        while (count >= requestQueue.length) {  

            try {  

                wait();  

            } catch (InterruptedException e) {  

            }  

        }  

        requestQueue[tail] = request;  

        tail = (tail + 1) % requestQueue.length;  

        count++;  

        notifyAll();  

    }  

    public synchronized Request takeRequest() {//从队列取出请求   

        while (count <= 0) {  

            try {  

                wait();  

            } catch (InterruptedException e) {  

            }  

        }  

        Request request = requestQueue[head];  

        head = (head + 1) % requestQueue.length;  

        count--;  

        notifyAll();  

        return request;  

    }  

}  

 channel类把传给他的请求放入队列中,等待worker去取请求,下面看看worker(即工作线程,线程池中已经初始话好的线程)

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();//处理请求   

        }  

    }  

}  

 在工作线程中会从线程池的队列里取出请求,并对请求进行处理。这里的workerthread相当于背景线程,他一直都在运行,当有请求的时候,他就会进行处理,这里处理请求的线程是已经存在在channel(线程池里的线程),他不会因为请求的增加而增加(这是本例中的情况),不会来一个请求就新建立一个线程,节省了资源。

 

再看看请求的代码:

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) {  

        }  

    }  

    public String toString() {  

        return "[ Request from " + name + " No." + number + " ]";  

    }  

}  

 JAVA SDK所写的 ExecutorService,其就相当于channel,即线程池。至于其实现当然要比channel复杂多了,channel只是举个例子。而WorkerThread可不是工作线程,他相当于发送到channel的请求,也就是request,当执行代码:tpes.execute(workers[i]);时,相当于向线程池加入一个请求,而WorkerThread中的run则相当于request中的execute,这也是当执行tpes.execute(workers[i]);时,并不会产生新的线程的原因。ExecutorService中产生的背景线程(相当于本篇的WorkerThread )我们是看不到的。

获取各种it视频

转载于:https://my.oschina.net/u/3385288/blog/1787129

相关文章:

  • Akamai 发布互联网安全报告:DDoS 攻击量激增
  • Android 采用AOP方式封装6.0权限管理
  • WebMIS 2016-09 稳定版,基于 Phalcon 的 CMS
  • 实验吧_加了料的报错注入
  • 常用的去重和排序
  • 记一例DCDIAG /A报错0x6ba rpc服务器不可用
  • 看直播卡顿问题,排除网络卡顿,排除cpu太差
  • Windows 10 RedStone 新版 Edge 浏览器上手图集
  • python数据类型之集合
  • javaWeb服务详解(含源代码,测试通过,注释) ——Emp的Service层
  • E - Box of Bricks (注意很多文章是错的)
  • centos安装iftop监控服务器流量
  • 【laravel5.4】重定向带参数
  • 基数排序
  • PHP array_walk() 函数
  • 【跃迁之路】【669天】程序员高效学习方法论探索系列(实验阶段426-2018.12.13)...
  • iOS仿今日头条、壁纸应用、筛选分类、三方微博、颜色填充等源码
  • Vue.js-Day01
  • Vue小说阅读器(仿追书神器)
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 记录:CentOS7.2配置LNMP环境记录
  • 力扣(LeetCode)21
  • 马上搞懂 GeoJSON
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 手机端车牌号码键盘的vue组件
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 鱼骨图 - 如何绘制?
  • 走向全栈之MongoDB的使用
  • 积累各种好的链接
  • #HarmonyOS:Web组件的使用
  • (10)ATF MMU转换表
  • (27)4.8 习题课
  • (C语言)fread与fwrite详解
  • (C语言)求出1,2,5三个数不同个数组合为100的组合个数
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (十一)手动添加用户和文件的特殊权限
  • (一)eclipse Dynamic web project 工程目录以及文件路径问题
  • (转)德国人的记事本
  • (转)甲方乙方——赵民谈找工作
  • *Algs4-1.5.25随机网格的倍率测试-(未读懂题)
  • .Net 4.0并行库实用性演练
  • .Net core 6.0 升8.0
  • .net core webapi 部署iis_一键部署VS插件:让.NET开发者更幸福
  • .net core使用ef 6
  • .NET 分布式技术比较
  • .NET 依赖注入和配置系统
  • .NET/C# 将一个命令行参数字符串转换为命令行参数数组 args
  • .netcore如何运行环境安装到Linux服务器
  • .NET中使用Redis (二)
  • .sys文件乱码_python vscode输出乱码
  • /3GB和/USERVA开关
  • @property @synthesize @dynamic 及相关属性作用探究
  • []AT 指令 收发短信和GPRS上网 SIM508/548
  • [AutoSar]BSW_OS 01 priority ceiling protocol(PCP)
  • [C# 网络编程系列]专题六:UDP编程