什么是JUC?

JUC就是java.util.concurrent包,这个包俗称JUC,里面都是解决并发问题的一些东西
该包的位置位于java下面的rt.jar包下面

4大常用并发工具类:

CountDownLatch
CyclicBarrier
Semaphore
ExChanger

CountDownLatch:

CountDownLatch,俗称闭锁,作用是类似加强版的Join,是让一组线程等待其他的线程完成工作以后才执行

就比如在启动框架服务的时候,我们主线程需要在环境线程初始化完成之后才能启动,这时候我们就可以实现使用CountDownLatch来完成

  1. /**
  2. * Constructs a {@code CountDownLatch} initialized with the given count.
  3. *
  4. * @param count the number of times {@link #countDown} must be invoked
  5. * before threads can pass through {@link #await}
  6. * @throws IllegalArgumentException if {@code count} is negative
  7. */
  8. public CountDownLatch(int count) {
  9. if (count < 0) throw new IllegalArgumentException("count < 0");
  10. this.sync = new Sync(count);
  11. }

在源码中可以看到,创建CountDownLatch时,需要传入一个int类型的参数,将决定在执行几次扣减之后,等待的线程被唤醒
微信图片_20211013151147.png
通过这个类图就可以知道其实CountDownLatch并没有多少东西
方法介绍:
CountDownLatch:初始化方法
await:等待方法,同时带参数的是超时重载方法
countDown:每执行一次,计数器减一,就是初始化传入的数字,也代表着一个线程完成了任务
getCount:获取当前值
toString:这个就不用说了

面的Sync是一个内部类,外面的方法其实都是操作这个内部类的,这个内部类继承了AQS,实现的标准方法,AQS将在后面的章节写

2.png
主线程中创建CountDownLatch(3),然后主线程await阻塞,然后线程A,B,C各自完成了任务,调用了countDown,之后,每个线程调用一次计数器就会减一,初始是3,然后A线程调用后变成2,B线程调用后变成1,C线程调用后,变成0,这时就会唤醒正在await的主线程,然后主线程继续执行

代码示例:
休眠工具类,之后的代码都会用到

  1. package org.dance.tools;
  2. import java.util.concurrent.TimeUnit;
  3. /**
  4. * 类说明:线程休眠辅助工具类
  5. */
  6. public class SleepTools {
  7. /**
  8. * 按秒休眠
  9. * @param seconds 秒数
  10. */
  11. public static final void second(int seconds) {
  12. try {
  13. TimeUnit.SECONDS.sleep(seconds);
  14. } catch (InterruptedException e) {
  15. }
  16. }
  17. /**
  18. * 按毫秒数休眠
  19. * @param seconds 毫秒数
  20. */
  21. public static final void ms(int seconds) {
  22. try {
  23. TimeUnit.MILLISECONDS.sleep(seconds);
  24. } catch (InterruptedException e) {
  25. }
  26. }
  27. }
  1. package org.dance.day2.util;
  2. import org.dance.tools.SleepTools;
  3. import java.util.concurrent.CountDownLatch;
  4. /**
  5. * CountDownLatch的使用,有五个线程,6个扣除点
  6. * 扣除完成后主线程和业务线程,才能执行工作
  7. * 扣除点一般都是大于等于需要初始化的线程的
  8. * @author ZYGisComputer
  9. */
  10. public class UseCountDownLatch {
  11. /**
  12. * 设置为6个扣除点
  13. */
  14. static CountDownLatch countDownLatch = new CountDownLatch(6);
  15. /**
  16. * 初始化线程
  17. */
  18. private static class InitThread implements Runnable {
  19. @Override
  20. public void run() {
  21. System.out.println("thread_" + Thread.currentThread().getId() + " ready init work .....");
  22. // 执行扣减 扣减不代表结束
  23. countDownLatch.countDown();
  24. for (int i = 0; i < 2; i++) {
  25. System.out.println("thread_" + Thread.currentThread().getId() + ".....continue do its work");
  26. }
  27. }
  28. }
  29. /**
  30. * 业务线程
  31. */
  32. private static class BusiThread implements Runnable {
  33. @Override
  34. public void run() {
  35. // 业务线程需要在等初始化完毕后才能执行
  36. try {
  37. countDownLatch.await();
  38. for (int i = 0; i < 3; i++) {
  39. System.out.println("BusiThread " + Thread.currentThread().getId() + " do business-----");
  40. }
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  46. public static void main(String[] args) {
  47. // 创建单独的初始化线程
  48. new Thread(){
  49. @Override
  50. public void run() {
  51. SleepTools.ms(1);
  52. System.out.println("thread_" + Thread.currentThread().getId() + " ready init work step 1st.....");
  53. // 扣减一次
  54. countDownLatch.countDown();
  55. System.out.println("begin stop 2nd.....");
  56. SleepTools.ms(1);
  57. System.out.println("thread_" + Thread.currentThread().getId() + " ready init work step 2nd.....");
  58. // 扣减一次
  59. countDownLatch.countDown();
  60. }
  61. }.start();
  62. // 启动业务线程
  63. new Thread(new BusiThread()).start();
  64. // 启动初始化线程
  65. for (int i = 0; i <= 3; i++) {
  66. new Thread(new InitThread()).start();
  67. }
  68. // 主线程进入等待
  69. try {
  70. countDownLatch.await();
  71. System.out.println("Main do ites work.....");
  72. } catch (InterruptedException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. }

返回结果:

  1. thread_13 ready init work .....
  2. thread_13.....continue do its work
  3. thread_13.....continue do its work
  4. thread_14 ready init work .....
  5. thread_14.....continue do its work
  6. thread_14.....continue do its work
  7. thread_15 ready init work .....
  8. thread_15.....continue do its work
  9. thread_11 ready init work step 1st.....
  10. begin stop 2nd.....
  11. thread_16 ready init work .....
  12. thread_16.....continue do its work
  13. thread_16.....continue do its work
  14. thread_15.....continue do its work
  15. thread_11 ready init work step 2nd.....
  16. Main do ites work.....
  17. BusiThread 12 do business-----
  18. BusiThread 12 do business-----
  19. BusiThread 12 do business-----

通过返回结果就可以很直接的看到业务线程是在初始化线程完全跑完之后,才开始执行的

CyclicBarrier:

CyclicBarrier,俗称栅栏锁,作用是让一组线程到达某个屏障,被阻塞,一直到组内的最后一个线程到达,然后屏障开放,接着,所有的线程继续运行
这个感觉和CountDownLatch有点相似,但是其实是不一样的,所谓的差别,将在下面详解

CyclicBarrier的构造参数有两个

  1. /**
  2. * Creates a new {@code CyclicBarrier} that will trip when the
  3. * given number of parties (threads) are waiting upon it, and
  4. * does not perform a predefined action when the barrier is tripped.
  5. *
  6. * @param parties the number of threads that must invoke {@link #await}
  7. * before the barrier is tripped
  8. * @throws IllegalArgumentException if {@code parties} is less than 1
  9. */
  10. public CyclicBarrier(int parties) {
  11. this(parties, null);
  12. }
  1. /**
  2. * Creates a new {@code CyclicBarrier} that will trip when the
  3. * given number of parties (threads) are waiting upon it, and which
  4. * will execute the given barrier action when the barrier is tripped,
  5. * performed by the last thread entering the barrier.
  6. *
  7. * @param parties the number of threads that must invoke {@link #await}
  8. * before the barrier is tripped
  9. * @param barrierAction the command to execute when the barrier is
  10. * tripped, or {@code null} if there is no action
  11. * @throws IllegalArgumentException if {@code parties} is less than 1
  12. */
  13. public CyclicBarrier(int parties, Runnable barrierAction) {
  14. if (parties <= 0) throw new IllegalArgumentException();
  15. this.parties = parties;
  16. this.count = parties;
  17. this.barrierCommand = barrierAction;
  18. }

很明显能感觉出来,上面的构造参数调用了下面的构造参数,是一个构造方法重载

首先这个第一个参数也是Int类型的,传入的是执行线程的个数,这个数量和CountDownLatch不一样,这个数量是需要和线程数量吻合的,CountDownLatch则不一样,CountDownLatch可以大于等于,而CyclicBarrier只能等于,然后是第二个参数,第二个参数是barrierAction,这个参数是当屏障开放后,执行的任务线程,如果当屏障开放后需要执行什么任务,可以写在这个线程中
3.png
主线程创建CyclicBarrier(3,barrierAction),然后由线程开始执行,线程A,B执行完成后都调用了await,然后他们都在一个屏障前阻塞者,需要等待线程C也,执行完成,调用await之后,然后三个线程都达到屏障后,屏障开放,然后线程继续执行,并且barrierAction在屏障开放的一瞬间也开始执行

代码示例:

  1. package org.dance.day2.util;
  2. import org.dance.tools.SleepTools;
  3. import java.util.Map;
  4. import java.util.Random;
  5. import java.util.concurrent.BrokenBarrierException;
  6. import java.util.concurrent.ConcurrentHashMap;
  7. import java.util.concurrent.CyclicBarrier;
  8. /**
  9. * CyclicBarrier的使用
  10. *
  11. * @author ZYGisComputer
  12. */
  13. public class UseCyclicBarrier {
  14. /**
  15. * 存放子线程工作结果的安全容器
  16. */
  17. private static ConcurrentHashMap<String, Long> resultMap = new ConcurrentHashMap<>();
  18. private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5,new CollectThread());
  19. /**
  20. * 结果打印线程
  21. * 用来演示CyclicBarrier的第二个参数,barrierAction
  22. */
  23. private static class CollectThread implements Runnable {
  24. @Override
  25. public void run() {
  26. StringBuffer result = new StringBuffer();
  27. for (Map.Entry<String, Long> workResult : resultMap.entrySet()) {
  28. result.append("[" + workResult.getValue() + "]");
  29. }
  30. System.out.println("the result = " + result);
  31. System.out.println("do other business.....");
  32. }
  33. }
  34. /**
  35. * 工作子线程
  36. * 用于CyclicBarrier的一组线程
  37. */
  38. private static class SubThread implements Runnable {
  39. @Override
  40. public void run() {
  41. // 获取当前线程的ID
  42. long id = Thread.currentThread().getId();
  43. // 放入统计容器中
  44. resultMap.put(String.valueOf(id), id);
  45. Random random = new Random();
  46. try {
  47. if (random.nextBoolean()) {
  48. Thread.sleep(1000 + id);
  49. System.out.println("Thread_"+id+"..... do something");
  50. }
  51. System.out.println(id+" is await");
  52. cyclicBarrier.await();
  53. Thread.sleep(1000+id);
  54. System.out.println("Thread_"+id+".....do its business");
  55. } catch (InterruptedException e) {
  56. e.printStackTrace();
  57. } catch (BrokenBarrierException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }
  62. public static void main(String[] args) {
  63. for (int i = 0; i <= 4; i++) {
  64. Thread thread = new Thread(new SubThread());
  65. thread.start();
  66. }
  67. }
  68. }

返回结果:

  1. 11 is await
  2. 14 is await
  3. 15 is await
  4. Thread_12..... do something
  5. 12 is await
  6. Thread_13..... do something
  7. 13 is await
  8. the result = [11][12][13][14][15]
  9. do other business.....
  10. Thread_11.....do its business
  11. Thread_12.....do its business
  12. Thread_13.....do its business
  13. Thread_14.....do its business
  14. Thread_15.....do its business

通过返回结果可以看出前面的11 14 15三个线程没有进入if语句块,在执行到await的时候进入了等待,而另外12 13两个线程进入到了if语句块当中,多休眠了1秒多,然后当5个线程同时到达await的时候,屏障开放,执行了barrierAction线程,然后线程组继续执行

CountDownLatch和CyclicBarrier的区别:
首先就是CountDownLatch的构造参数传入的数量一般都是大于等于线程的数量,因为他是有第三方控制的,可以扣减多次,然后就是CyclicBarrier的构造参数第一个参数传入的数量一定是等于线程的个数的,因为他是由一组线程自身控制的

  1. CountDownLatch CyclicBarrier<br />控制 第三方控制 自身控制<br />传入数量 大于等于线程数量 等于线程数量

Semaphore:

Semaphore,俗称信号量,作用于控制同时访问某个特定资源的线程数量,用在流量控制
一说特定资源控制,那么第一时间就想到了数据库连接..

示例:用Semaphone写一个数据库连接池

  1. /**
  2. * Creates a {@code Semaphore} with the given number of
  3. * permits and nonfair fairness setting.
  4. *
  5. * @param permits the initial number of permits available.
  6. * This value may be negative, in which case releases
  7. * must occur before any acquires will be granted.
  8. */
  9. public Semaphore(int permits) {
  10. sync = new NonfairSync(permits);
  11. }

在源码中可以看到在构建Semaphore信号量的时候,需要传入许可证的数量,这个数量就是资源的最大允许访问的线程数

接下里用信号量实现一个数据库连接池

连接对象

  1. package org.dance.day2.util.pool;
  2. import org.dance.tools.SleepTools;
  3. import java.sql.*;
  4. import java.util.Map;
  5. import java.util.Properties;
  6. import java.util.concurrent.Executor;
  7. /**
  8. * 数据库连接
  9. * @author ZYGisComputer
  10. */
  11. public class SqlConnection implements Connection {
  12. /**
  13. * 获取数据库连接
  14. * @return
  15. */
  16. public static final Connection fetchConnection(){
  17. return new SqlConnection();
  18. }
  19. @Override
  20. public void commit() throws SQLException {
  21. SleepTools.ms(70);
  22. }
  23. @Override
  24. public Statement createStatement() throws SQLException {
  25. SleepTools.ms(1);
  26. return null;
  27. }
  28. @Override
  29. public PreparedStatement prepareStatement(String sql) throws SQLException {
  30. return null;
  31. }
  32. @Override
  33. public CallableStatement prepareCall(String sql) throws SQLException {
  34. return null;
  35. }
  36. @Override
  37. public String nativeSQL(String sql) throws SQLException {
  38. return null;
  39. }
  40. @Override
  41. public void setAutoCommit(boolean autoCommit) throws SQLException {
  42. }
  43. @Override
  44. public boolean getAutoCommit() throws SQLException {
  45. return false;
  46. }
  47. @Override
  48. public void rollback() throws SQLException {
  49. }
  50. @Override
  51. public void close() throws SQLException {
  52. }
  53. @Override
  54. public boolean isClosed() throws SQLException {
  55. return false;
  56. }
  57. @Override
  58. public DatabaseMetaData getMetaData() throws SQLException {
  59. return null;
  60. }
  61. @Override
  62. public void setReadOnly(boolean readOnly) throws SQLException {
  63. }
  64. @Override
  65. public boolean isReadOnly() throws SQLException {
  66. return false;
  67. }
  68. @Override
  69. public void setCatalog(String catalog) throws SQLException {
  70. }
  71. @Override
  72. public String getCatalog() throws SQLException {
  73. return null;
  74. }
  75. @Override
  76. public void setTransactionIsolation(int level) throws SQLException {
  77. }
  78. @Override
  79. public int getTransactionIsolation() throws SQLException {
  80. return 0;
  81. }
  82. @Override
  83. public SQLWarning getWarnings() throws SQLException {
  84. return null;
  85. }
  86. @Override
  87. public void clearWarnings() throws SQLException {
  88. }
  89. @Override
  90. public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
  91. return null;
  92. }
  93. @Override
  94. public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
  95. return null;
  96. }
  97. @Override
  98. public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
  99. return null;
  100. }
  101. @Override
  102. public Map<String, Class<?>> getTypeMap() throws SQLException {
  103. return null;
  104. }
  105. @Override
  106. public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
  107. }
  108. @Override
  109. public void setHoldability(int holdability) throws SQLException {
  110. }
  111. @Override
  112. public int getHoldability() throws SQLException {
  113. return 0;
  114. }
  115. @Override
  116. public Savepoint setSavepoint() throws SQLException {
  117. return null;
  118. }
  119. @Override
  120. public Savepoint setSavepoint(String name) throws SQLException {
  121. return null;
  122. }
  123. @Override
  124. public void rollback(Savepoint savepoint) throws SQLException {
  125. }
  126. @Override
  127. public void releaseSavepoint(Savepoint savepoint) throws SQLException {
  128. }
  129. @Override
  130. public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
  131. return null;
  132. }
  133. @Override
  134. public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
  135. return null;
  136. }
  137. @Override
  138. public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
  139. return null;
  140. }
  141. @Override
  142. public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
  143. return null;
  144. }
  145. @Override
  146. public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
  147. return null;
  148. }
  149. @Override
  150. public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
  151. return null;
  152. }
  153. @Override
  154. public Clob createClob() throws SQLException {
  155. return null;
  156. }
  157. @Override
  158. public Blob createBlob() throws SQLException {
  159. return null;
  160. }
  161. @Override
  162. public NClob createNClob() throws SQLException {
  163. return null;
  164. }
  165. @Override
  166. public SQLXML createSQLXML() throws SQLException {
  167. return null;
  168. }
  169. @Override
  170. public boolean isValid(int timeout) throws SQLException {
  171. return false;
  172. }
  173. @Override
  174. public void setClientInfo(String name, String value) throws SQLClientInfoException {
  175. }
  176. @Override
  177. public void setClientInfo(Properties properties) throws SQLClientInfoException {
  178. }
  179. @Override
  180. public String getClientInfo(String name) throws SQLException {
  181. return null;
  182. }
  183. @Override
  184. public Properties getClientInfo() throws SQLException {
  185. return null;
  186. }
  187. @Override
  188. public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
  189. return null;
  190. }
  191. @Override
  192. public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
  193. return null;
  194. }
  195. @Override
  196. public void setSchema(String schema) throws SQLException {
  197. }
  198. @Override
  199. public String getSchema() throws SQLException {
  200. return null;
  201. }
  202. @Override
  203. public void abort(Executor executor) throws SQLException {
  204. }
  205. @Override
  206. public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
  207. }
  208. @Override
  209. public int getNetworkTimeout() throws SQLException {
  210. return 0;
  211. }
  212. @Override
  213. public <T> T unwrap(Class<T> iface) throws SQLException {
  214. return null;
  215. }
  216. @Override
  217. public boolean isWrapperFor(Class<?> iface) throws SQLException {
  218. return false;
  219. }
  220. }

连接池对象

  1. package org.dance.day2.util.pool;
  2. import java.sql.Connection;
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.LinkedList;
  7. import java.util.concurrent.Semaphore;
  8. /**
  9. * 使用信号量控制数据库的链接和释放
  10. *
  11. * @author ZYGisComputer
  12. */
  13. public class DBPoolSemaphore {
  14. /**
  15. * 池容量
  16. */
  17. private final static int POOL_SIZE = 10;
  18. /**
  19. * useful 代表可用连接
  20. * useless 代表已用连接
  21. * 为什么要使用两个Semaphore呢?是因为,在连接池中不只有连接本身是资源,空位也是资源,也需要记录
  22. */
  23. private final Semaphore useful, useless;
  24. /**
  25. * 连接池
  26. */
  27. private final static LinkedList<Connection> POOL = new LinkedList<>();
  28. /**
  29. * 使用静态块初始化池
  30. */
  31. static {
  32. for (int i = 0; i < POOL_SIZE; i++) {
  33. POOL.addLast(SqlConnection.fetchConnection());
  34. }
  35. }
  36. public DBPoolSemaphore() {
  37. // 初始可用的许可证等于池容量
  38. useful = new Semaphore(POOL_SIZE);
  39. // 初始不可用的许可证容量为0
  40. useless = new Semaphore(0);
  41. }
  42. /**
  43. * 获取数据库连接
  44. *
  45. * @return 连接对象
  46. */
  47. public Connection takeConnection() throws InterruptedException {
  48. // 可用许可证减一
  49. useful.acquire();
  50. Connection connection;
  51. synchronized (POOL) {
  52. connection = POOL.removeFirst();
  53. }
  54. // 不可用许可证数量加一
  55. useless.release();
  56. return connection;
  57. }
  58. /**
  59. * 释放链接
  60. *
  61. * @param connection 连接对象
  62. */
  63. public void returnConnection(Connection connection) throws InterruptedException {
  64. if(null!=connection){
  65. // 打印日志
  66. System.out.println("当前有"+useful.getQueueLength()+"个线程等待获取连接,,"
  67. +"可用连接有"+useful.availablePermits()+"个");
  68. // 不可用许可证减一
  69. useless.acquire();
  70. synchronized (POOL){
  71. POOL.addLast(connection);
  72. }
  73. // 可用许可证加一
  74. useful.release();
  75. }
  76. }
  77. }

测试类:

  1. package org.dance.day2.util.pool;
  2. import org.dance.tools.SleepTools;
  3. import java.sql.Connection;
  4. import java.util.Random;
  5. /**
  6. * 测试Semaphore
  7. * @author ZYGisComputer
  8. */
  9. public class UseSemaphore {
  10. /**
  11. * 连接池
  12. */
  13. public static final DBPoolSemaphore pool = new DBPoolSemaphore();
  14. private static class BusiThread extends Thread{
  15. @Override
  16. public void run() {
  17. // 随机数工具类 为了让每个线程持有连接的时间不一样
  18. Random random = new Random();
  19. long start = System.currentTimeMillis();
  20. try {
  21. Connection connection = pool.takeConnection();
  22. System.out.println("Thread_"+Thread.currentThread().getId()+
  23. "_获取数据库连接耗时["+(System.currentTimeMillis()-start)+"]ms.");
  24. // 模拟使用连接查询数据
  25. SleepTools.ms(100+random.nextInt(100));
  26. System.out.println("查询数据完成归还连接");
  27. pool.returnConnection(connection);
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  33. public static void main(String[] args) {
  34. for (int i = 0; i < 50; i++) {
  35. BusiThread busiThread = new BusiThread();
  36. busiThread.start();
  37. }
  38. }
  39. }

测试返回结果:

  1. Thread_11_获取数据库连接耗时[0]ms.
  2. Thread_12_获取数据库连接耗时[0]ms.
  3. Thread_13_获取数据库连接耗时[0]ms.
  4. Thread_14_获取数据库连接耗时[0]ms.
  5. Thread_15_获取数据库连接耗时[0]ms.
  6. Thread_16_获取数据库连接耗时[0]ms.
  7. Thread_17_获取数据库连接耗时[0]ms.
  8. Thread_18_获取数据库连接耗时[0]ms.
  9. Thread_19_获取数据库连接耗时[0]ms.
  10. Thread_20_获取数据库连接耗时[0]ms.
  11. 查询数据完成归还连接
  12. 当前有40个线程等待获取连接,,可用连接有0
  13. Thread_21_获取数据库连接耗时[112]ms.
  14. 查询数据完成归还连接
  15. ...................
  16. 查询数据完成归还连接
  17. 当前有2个线程等待获取连接,,可用连接有0
  18. Thread_59_获取数据库连接耗时[637]ms.
  19. 查询数据完成归还连接
  20. 当前有1个线程等待获取连接,,可用连接有0
  21. Thread_60_获取数据库连接耗时[660]ms.
  22. 查询数据完成归还连接
  23. 当前有0个线程等待获取连接,,可用连接有0
  24. 查询数据完成归还连接
  25. ...................
  26. 当前有0个线程等待获取连接,,可用连接有8
  27. 查询数据完成归还连接
  28. 当前有0个线程等待获取连接,,可用连接有9

通过执行结果可以很明确的看到,一上来就有10个线程获取到了连接,,然后后面的40个线程进入阻塞,然后只有释放链接之后,等待的线程就会有一个拿到,然后越后面的线程等待的时间就越长,然后一直到所有的线程执行完毕
最后打印的可用连接有九个不是因为少了一个是因为在释放之前打印的,不是错误
从结果中可以看到,我们对连接池中的资源的到了控制,这就是信号量的流量控制

Exchanger:

Exchanger,俗称交换器,用于在线程之间交换数据,但是比较受限,因为只能两个线程之间交换数据

  1. /**
  2. * Creates a new Exchanger.
  3. */
  4. public Exchanger() {
  5. participant = new Participant();
  6. }

这个构造函数没有什么好说的,也没有入参,只有在创建的时候指定一下需要交换的数据的泛型即可,下面看代码

  1. package org.dance.day2.util;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. import java.util.concurrent.Exchanger;
  5. /**
  6. * 线程之间交换数据
  7. * @author ZYGisComputer
  8. */
  9. public class UseExchange {
  10. private static final Exchanger<Set<String>> exchanger = new Exchanger<>();
  11. public static void main(String[] args) {
  12. new Thread(){
  13. @Override
  14. public void run() {
  15. Set<String> aSet = new HashSet<>();
  16. aSet.add("A");
  17. aSet.add("B");
  18. aSet.add("C");
  19. try {
  20. Set<String> exchange = exchanger.exchange(aSet);
  21. for (String s : exchange) {
  22. System.out.println("aSet"+s);
  23. }
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }.start();
  29. new Thread(){
  30. @Override
  31. public void run() {
  32. Set<String> bSet = new HashSet<>();
  33. bSet.add("1");
  34. bSet.add("2");
  35. bSet.add("3");
  36. try {
  37. Set<String> exchange = exchanger.exchange(bSet);
  38. for (String s : exchange) {
  39. System.out.println("bSet"+s);
  40. }
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }.start();
  46. }
  47. }

执行结果:

  1. bSetA
  2. bSetB
  3. bSetC
  4. aSet1
  5. aSet2
  6. aSet3

通过执行结果可以清晰的看到,两个线程中的数据发生了交换,这就是Exchanger的线程数据交换了