博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Semaphore使用
阅读量:4230 次
发布时间:2019-05-26

本文共 2171 字,大约阅读时间需要 7 分钟。

单词Semaphore的中文含义是信号、信号系统。此类的主要作用就是限制线程并发的数量,如果不限制线程并发的数量,则cup的资源很快就被耗尽,每个线程执行的任务是相当缓慢,因为cup要把时间片分配给不同的线程对象,而且上下文切换也要耗时,最终造成系统运行效率大幅降低,所以限制并发线程的数量很有必要

1. 简单使用

  1. 举个栗子
public class Service {
private Semaphore semaphore = new Semaphore(2); public void testMethod() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis()); Thread.sleep(5000); System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis()); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } }}public class ThreadA extends Thread {
private Service service; public ThreadA(Service service) { super(); this.service = service; } @Override public void run() { service.testMethod(); }}public class Run {
public static void main(String[] args) { Service service=new Service(); ThreadA a=new ThreadA(service); a.setName("A"); ThreadA b=new ThreadA(service); b.setName("B"); ThreadA c=new ThreadA(service); c.setName("C"); a.start(); b.start(); c.start(); }}

运行效果:

B begin timer=1518577498811A begin timer=1518577498812B end timer=1518577503812C begin timer=1518577503812A end timer=1518577503812C end timer=1518577508812

可以发现,虽然同时打开了三个线程,但是只有两个线程可以并发执行。

2. 使用Semaphore创建字符串池

类Semaphore可以有效地对并发执行任务的线程数量进行限制,这种功能可以应用在pool池技术中,可以设置同时访问pool池中数据的线程数量。

本实验的功能是同时有若干线程可以访问池中的数据,但同时只有一个线程可以取得数据,使用完毕后再放回池中。

public class ListPool {    private int poolMaxSize=3;    private int semaphorePermits=5;    private List
list=new ArrayList<>(); private Semaphore concurrencySemaphore=new Semaphore(semaphorePermits); private ReentrantLock lock=new ReentrantLock(); private Condition condition=lock.newCondition(); public ListPool(){ super(); for(int i=0;i
  • 运行结果
Thread-2 取得值 test1Thread-3 取得值 test2Thread-2 取得值 test1Thread-5 取得值 test1Thread-1 取得值 test1Thread-1 取得值 test1Thread-0 取得值 test3Thread-1 取得值 test1Thread-10 取得值 test3...............

转载地址:http://tqjqi.baihongyu.com/

你可能感兴趣的文章
Msgpack有没有兴趣了解一下?
查看>>
探索一家神秘的公司
查看>>
PDF转Word完全免费?这么好的事情我怎么不知道????
查看>>
数据解读---B站火过蔡徐坤的“鬼畜“区巨头们
查看>>
Squid代理服务器搭建亿级爬虫IP代理池
查看>>
JupyterNotebook‘s Magic
查看>>
在Linux 上部署Jenkins和项目
查看>>
Python+requests+unittest+excel实现接口自动化测试框架
查看>>
那些年我们听过的互联网公司的套路?
查看>>
谈谈python里面那些高级函数
查看>>
40行代码带你免费看《海贼王-和之国》篇章
查看>>
搭建炫酷的服务器监控平台
查看>>
垃圾分类:人机搭配,干活不累
查看>>
Nginx
查看>>
Memcached,session共享
查看>>
Tomcat,varnish
查看>>
SVN, 制作RPM包
查看>>
HTML 标签说明
查看>>
CSS 基本语法
查看>>
10.shell基础
查看>>