资讯专栏INFORMATION COLUMN

java多线程信号量-semaphore

zzbo / 3073人阅读

摘要:年月日上午阿里云消息服,队列消息发送以及消费的并发测试解析配置文件二者等价线程数并发数程序入口准备工作发送消息线程池一个计数信号量。但是,不使用实际的许可对象,只对可用许可的号码进行计数,并采取相应的行动。

</>复制代码

  1. package com.study.mq.aliyunmns;
  2. import java.io.BufferedInputStream;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.net.URL;
  7. import java.util.Properties;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.Semaphore;
  11. import org.apache.commons.lang3.SystemUtils;
  12. import org.apache.log4j.Logger;
  13. import org.apache.log4j.PropertyConfigurator;
  14. import com.aliyun.mns.client.CloudAccount;
  15. import com.aliyun.mns.client.CloudQueue;
  16. import com.aliyun.mns.client.MNSClient;
  17. import com.aliyun.mns.common.http.ClientConfiguration;
  18. import com.aliyun.mns.model.Message;
  19. /**
  20. *
  21. * @author wangkai
  22. * @20161122日 上午11:27:14
  23. * @desc:阿里云消息服(MNS),队列消息发送以及消费的并发测试
  24. * https://www.aliyun.com/product/mns?spm=5176.8142029
  25. * .388261.80.fNnCkg
  26. */
  27. public class MnsQueueAppV2 {
  28. private static Logger LOG = Logger.getLogger(MnsQueueAppV2.class.getName());
  29. private static MNSClient client = null;
  30. // private static AtomicLong totalCount = new AtomicLong(0);
  31. private static String endpoint = null;
  32. private static String accessId = null;
  33. private static String accessKey = null;
  34. private static String queueName = "articlepricinglog";
  35. private static int threadNum = 100;
  36. private static int clientNum = 10000;
  37. // private static int totalSeconds = 180;
  38. private static String log4jConfPath = "./log4j.properties";
  39. static {
  40. PropertyConfigurator.configureAndWatch(log4jConfPath);
  41. }
  42. /**
  43. * 解析配置文件
  44. *
  45. * @return
  46. */
  47. @SuppressWarnings("unused")
  48. protected static boolean parseConf() {
  49. // URL resource =
  50. // MnsQueueAppV2.class.getClassLoader().getResource("name.properties");
  51. String confFilePath = SystemUtils.getUserDir()
  52. + SystemUtils.FILE_SEPARATOR
  53. + "src/main/resources/mns.properties";
  54. URL resource = MnsQueueAppV2.class.getResource("/mns.properties");
  55. URL resource2 = MnsQueueAppV2.class.getClassLoader().getResource(
  56. "mns.properties");// 二者等价
  57. BufferedInputStream bis = null;
  58. try {
  59. bis = new BufferedInputStream(new FileInputStream(confFilePath));
  60. if (bis == null) {
  61. LOG.info("ConfFile not opened: " + confFilePath);
  62. return false;
  63. }
  64. } catch (FileNotFoundException e) {
  65. LOG.error("ConfFile not found: " + confFilePath, e);
  66. return false;
  67. }
  68. // load file
  69. Properties properties = new Properties();
  70. try {
  71. properties.load(bis);
  72. } catch (IOException e) {
  73. LOG.error("Load ConfFile Failed: " + e.getMessage());
  74. return false;
  75. } finally {
  76. try {
  77. bis.close();
  78. } catch (Exception e) {
  79. // do nothing
  80. }
  81. }
  82. // init the member parameters
  83. endpoint = properties.getProperty("Endpoint");
  84. LOG.info("Endpoint: " + endpoint);
  85. accessId = properties.getProperty("AccessId");
  86. LOG.info("AccessId: " + accessId);
  87. accessKey = properties.getProperty("AccessKey");
  88. queueName = properties.getProperty("QueueName", queueName);
  89. LOG.info("QueueName: " + queueName);
  90. threadNum = Integer.parseInt(properties.getProperty("ThreadNum",
  91. String.valueOf(threadNum)));
  92. LOG.info("ThreadNum: 线程数" + threadNum);
  93. clientNum = Integer.parseInt(properties.getProperty("ClientNum",
  94. String.valueOf(clientNum)));
  95. LOG.info("ClientNum: 并发数" + clientNum);
  96. // totalSeconds =
  97. // Integer.parseInt(properties.getProperty("TotalSeconds",
  98. // String.valueOf(totalSeconds)));
  99. // LOG.info("TotalSeconds: " + totalSeconds);
  100. return true;
  101. }
  102. /**
  103. * 程序入口
  104. *
  105. * @param args
  106. * @throws InterruptedException
  107. */
  108. public static void main(String[] args) throws InterruptedException {
  109. // 准备工作
  110. if (!parseConf()) {
  111. return;
  112. }
  113. ClientConfiguration clientConfiguration = new ClientConfiguration();
  114. clientConfiguration.setMaxConnections(threadNum);
  115. clientConfiguration.setMaxConnectionsPerRoute(threadNum);
  116. CloudAccount cloudAccount = new CloudAccount(accessId, accessKey,
  117. endpoint, clientConfiguration);
  118. client = cloudAccount.getMNSClient();
  119. LOG.info("发送消息");
  120. // 线程池
  121. ExecutorService exec = Executors.newFixedThreadPool(500);
  122. /**
  123. * Semaphore 一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个
  124. * acquire(),然后再获取该许可。每个 release()
  125. * 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数
  126. * ,并采取相应的行动。拿到信号量的线程可以进入代码,否则就等待。通过acquire()和release()获取和释放访问许可。
  127. */
  128. final Semaphore semp = new Semaphore(threadNum);// ["seməfɔː]
  129. final Semaphore semaphore = new Semaphore(10, true);
  130. // 拿到信号量的线程可以进入代码,否则就等待
  131. // Semaphore(信号量)是用来控制同时访问特定资源的线程数量,它通过协调各个线程,以保证合理的使用公共资源
  132. // 辅助理解 :很多年以来,我都觉得从字面上很难理解Semaphore所表达的含义,只能把它比作是控制流量的红绿灯,
  133. // 比如XX马路要限制流量,只允许同时有一百辆车在这条路上行使,其他的都必须在路口等待,所以前一百辆车会看到绿灯,
  134. // 可以开进这条马路,后面的车会看到红灯,不能驶入XX马路,但是如果前一百辆中有五辆车已经离开了XX马路,
  135. // 那么后面就允许有5辆车驶入马路,这个例子里说的车就是线程,驶入马路就表示线程在执行,离开马路就表示线程执行完成,看见红灯就表示线程被阻塞,不能执行。
  136. long startTime = System.currentTimeMillis(); // 开启时间
  137. /**
  138. * 原理:
  139. * 更进一步,信号量的特性如下:信号量是一个非负整数(车位数),所有通过它的线程(车辆)都会将该整数减一(通过它当然是为了使用资源),
  140. * 当该整数值为零时,所有试图通过它的线程都将处于等待状态。在信号量上我们定义两种操作: Wait(等待) 和 Release(释放)。
  141. * 当一个线程调用Wait
  142. * (等待)操作时,它要么通过然后将信号量减一,要么一直等下去,直到信号量大于一或超时。Release(释放)实际上是在信号量上执行加操作
  143. * ,对应于车辆离开停车场,该操作之所以叫做“释放”是因为加操作实际上是释放了由信号量守护的资源。
  144. */
  145. // 开始
  146. for (int index = 0; index < clientNum; index++) {
  147. // final int NO = index;
  148. Runnable task = new Runnable() {
  149. public void run() {
  150. try {
  151. semp.acquire();// 获取许可
  152. try {
  153. // 获取queue
  154. CloudQueue queue = client.getQueueRef(queueName);
  155. // 组装消息
  156. Message message = new Message();
  157. message.setMessageBody("Test");
  158. // 发送消息
  159. queue.putMessage(message);
  160. } catch (Exception e) {
  161. e.printStackTrace();
  162. }
  163. semp.release();// 归还许可
  164. } catch (Exception e) {
  165. e.printStackTrace();
  166. }
  167. }
  168. };
  169. exec.submit(task);
  170. }
  171. long endTime = System.currentTimeMillis(); // 开启时间
  172. exec.shutdown();
  173. LOG.info(clientNum + " 的并发发送消息总耗时:>>>" + (endTime - startTime) + " ms");
  174. LOG.info(clientNum + " 的并发发送消息 QPS为:>>>" + (clientNum * 1000)
  175. / (endTime - startTime) + " q/s");
  176. LOG.info("接收消息");
  177. Thread.sleep(3000);
  178. ExecutorService exec2 = Executors.newFixedThreadPool(500);
  179. final Semaphore semp2 = new Semaphore(threadNum);
  180. long startTime2 = System.currentTimeMillis(); // 开启时间
  181. for (int index = 0; index < clientNum; index++) {
  182. // final int NO = index;
  183. Runnable task = new Runnable() {
  184. public void run() {
  185. try {
  186. semp2.acquire();
  187. try {
  188. // 获取queue
  189. CloudQueue queue = client.getQueueRef(queueName);
  190. // 获取消息
  191. Message message = queue.popMessage();
  192. // 删掉消息
  193. if (message != null)
  194. queue.deleteMessage(message.getReceiptHandle());
  195. } catch (Exception e) {
  196. e.printStackTrace();
  197. }
  198. semp2.release();
  199. } catch (Exception e) {
  200. e.printStackTrace();
  201. }
  202. }
  203. };
  204. exec2.submit(task);
  205. }
  206. long endTime2 = System.currentTimeMillis(); // 开启时间
  207. exec2.shutdown();
  208. // 忽略线程切换的耗时 精确的做法?
  209. LOG.info(clientNum + " 的并发接收消息总耗时:>>>" + (endTime2 - startTime2)

</>复制代码

  1. + " ms");
  2. LOG.info(clientNum + " 的并发接收消息 QPS为:>>>" + (clientNum * 1000)
  3. / (endTime2 - startTime2) + " q/s");
  4. }

}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66396.html

相关文章

  • Java线程工具箱之Semaphore

    摘要:多线程工具箱之前言这一篇谈一下信号量。信息信息信息信息信息信息信息信息信息信息信息小结适用于多线程请求数量资源的场景,但无法解决单多个线程对同一资源访问的竞争性访问。在后面我们在我们的多线程工具箱里面陆续会提到。 Java多线程工具箱之Semaphore 前言 这一篇谈一下Semaphore:信号量。 将Semaphore类比为为信号灯,被继承Runable的线程类比为列车:理解信号量...

    FleyX 评论0 收藏0
  • (八)java线程Semaphore

    摘要:在每个线程获取之前,必须先从信号量获取许可。注意,因为同时可能发生取消,所以返回并不保证有其他线程等待获取许可。该值仅是估计的数字,因为在此方法遍历内部数据结构的同时,线程的数目可能动态地变化。 本人邮箱: 欢迎转载,转载请注明网址 http://blog.csdn.net/tianshi_kcogithub: https://github.com/kco1989/kco代码已经全部托...

    DesGemini 评论0 收藏0
  • Java并发线程 - 并发工具类JUC

    摘要:将屏障重置为其初始状态。注意,在由于其他原因造成损坏之后,实行重置可能会变得很复杂此时需要使用其他方式重新同步线程,并选择其中一个线程来执行重置。 安全共享对象策略 1.线程限制 : 一个被线程限制的对象,由线程独占,并且只能被占有它的线程修改2.共享只读 : 一个共享只读的对象,在没有额外同步的情况下,可以被多个线程并发访问,但是任何线程都不能修改它3.线程安全对象 : 一个线程安全...

    wuyumin 评论0 收藏0
  • Java线程打辅助的三个小伙子

    摘要:前言之前学多线程的时候没有学习线程的同步工具类辅助类。而其它线程完成自己的操作后,调用使计数器减。信号量控制一组线程同时执行。 前言 之前学多线程的时候没有学习线程的同步工具类(辅助类)。ps:当时觉得暂时用不上,认为是挺高深的知识点就没去管了.. 在前几天,朋友发了一篇比较好的Semaphore文章过来,然后在浏览博客的时候又发现面试还会考,那还是挺重要的知识点。于是花了点时间去了解...

    pingink 评论0 收藏0
  • Java线程编程实战:模拟大量数据同步

    摘要:所以得出结论需要分配较多的线程进行读数据,较少的线程进行写数据。注意多线程编程对实际环境和需求有很大的依赖,需要根据实际的需求情况对各个参数做调整。 背景 最近对于 Java 多线程做了一段时间的学习,笔者一直认为,学习东西就是要应用到实际的业务需求中的。否则要么无法深入理解,要么硬生生地套用技术只是达到炫技的效果。 不过笔者仍旧认为自己对于多线程掌握不够熟练,不敢轻易应用到生产代码中...

    elliott_hu 评论0 收藏0

发表评论

0条评论

zzbo

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<