关键词搜索

源码搜索 ×
×

Java队列和线程池消费处理的简单设计

发布2020-12-03浏览1255次

详情内容

目录

实现目标 

目标分析

线程池设计

队列与线程池结合


实现目标 

  • 队列缓冲业务数据
  • 线程空闲忙碌识别
  • 任务处理的进度控制

目标分析

进度控制:需要将队列里面总任务和线程消费的任务进行记录,实现一个completed/total  这样的控制。

线程池控制:线程池使用计数器,在完成任务和新增任务进行原子操作维护计数器数量。

线程池设计

线程池实际上就是一个线程的池化处理,一般会初始化几个线程,需要使用线程时从池子里面拿,池子里面的总容量占用多少可以用来标记线程繁忙和空闲。线程池的设计跟数据库JDBC的设计非常相似。比如获取连接多久超时等等,在线程池里面也是可以这样来实现,线程的示例是用来执行任务的,线程池大小的个数不宜太大,一般core*2或者core*2+1 ,再或者凑个十进制十位整数。

队列Queue:队列可以是一个链表,也可以是一个简单的集合,需要设计相应的队列排队策略(入队、出队、优先级),还需要设计相应的方法来便于外部操作,Java队列主要有以下操作方法:

线程池:线程池的实现也有很多,比如最常用的Excutors的多种类型线程池,比如:

  • 自动伸缩类型线程池
  • 固定大小类型线程池
  • 单个线程池
  • 调度式线程池
  • 不可配置线程池...
  1. package java.util.concurrent;
  2. import java.util.*;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. import java.security.AccessControlContext;
  5. import java.security.AccessController;
  6. import java.security.PrivilegedAction;
  7. import java.security.PrivilegedExceptionAction;
  8. import java.security.PrivilegedActionException;
  9. import java.security.AccessControlException;
  10. import sun.security.util.SecurityConstants;
  11. /**
  12. * Factory and utility methods for {@link Executor}, {@link
  13. * ExecutorService}, {@link ScheduledExecutorService}, {@link
  14. * ThreadFactory}, and {@link Callable} classes defined in this
  15. * package. This class supports the following kinds of methods:
  16. *
  17. * <ul>
  18. * <li> Methods that create and return an {@link ExecutorService}
  19. * set up with commonly useful configuration settings.
  20. * <li> Methods that create and return a {@link ScheduledExecutorService}
  21. * set up with commonly useful configuration settings.
  22. * <li> Methods that create and return a "wrapped" ExecutorService, that
  23. * disables reconfiguration by making implementation-specific methods
  24. * inaccessible.
  25. * <li> Methods that create and return a {@link ThreadFactory}
  26. * that sets newly created threads to a known state.
  27. * <li> Methods that create and return a {@link Callable}
  28. * out of other closure-like forms, so they can be used
  29. * in execution methods requiring {@code Callable}.
  30. * </ul>
  31. *
  32. * @since 1.5
  33. * @author Doug Lea
  34. */
  35. public class Executors {
  36. /**
  37. * Creates a thread pool that reuses a fixed number of threads
  38. * operating off a shared unbounded queue. At any point, at most
  39. * {@code nThreads} threads will be active processing tasks.
  40. * If additional tasks are submitted when all threads are active,
  41. * they will wait in the queue until a thread is available.
  42. * If any thread terminates due to a failure during execution
  43. * prior to shutdown, a new one will take its place if needed to
  44. * execute subsequent tasks. The threads in the pool will exist
  45. * until it is explicitly {@link ExecutorService#shutdown shutdown}.
  46. *
  47. * @param nThreads the number of threads in the pool
  48. * @return the newly created thread pool
  49. * @throws IllegalArgumentException if {@code nThreads <= 0}
  50. */
  51. public static ExecutorService newFixedThreadPool(int nThreads) {
  52. return new ThreadPoolExecutor(nThreads, nThreads,
  53. 0L, TimeUnit.MILLISECONDS,
  54. new LinkedBlockingQueue<Runnable>());
  55. }
  56. /**
  57. * Creates a thread pool that maintains enough threads to support
  58. * the given parallelism level, and may use multiple queues to
  59. * reduce contention. The parallelism level corresponds to the
  60. * maximum number of threads actively engaged in, or available to
  61. * engage in, task processing. The actual number of threads may
  62. * grow and shrink dynamically. A work-stealing pool makes no
  63. * guarantees about the order in which submitted tasks are
  64. * executed.
  65. *
  66. * @param parallelism the targeted parallelism level
  67. * @return the newly created thread pool
  68. * @throws IllegalArgumentException if {@code parallelism <= 0}
  69. * @since 1.8
  70. */
  71. public static ExecutorService newWorkStealingPool(int parallelism) {
  72. return new ForkJoinPool
  73. (parallelism,
  74. ForkJoinPool.defaultForkJoinWorkerThreadFactory,
  75. null, true);
  76. }
  77. /**
  78. * Creates a work-stealing thread pool using all
  79. * {@link Runtime#availableProcessors available processors}
  80. * as its target parallelism level.
  81. * @return the newly created thread pool
  82. * @see #newWorkStealingPool(int)
  83. * @since 1.8
  84. */
  85. public static ExecutorService newWorkStealingPool() {
  86. return new ForkJoinPool
  87. (Runtime.getRuntime().availableProcessors(),
  88. ForkJoinPool.defaultForkJoinWorkerThreadFactory,
  89. null, true);
  90. }
  91. /**
  92. * Creates a thread pool that reuses a fixed number of threads
  93. * operating off a shared unbounded queue, using the provided
  94. * ThreadFactory to create new threads when needed. At any point,
  95. * at most {@code nThreads} threads will be active processing
  96. * tasks. If additional tasks are submitted when all threads are
  97. * active, they will wait in the queue until a thread is
  98. * available. If any thread terminates due to a failure during
  99. * execution prior to shutdown, a new one will take its place if
  100. * needed to execute subsequent tasks. The threads in the pool will
  101. * exist until it is explicitly {@link ExecutorService#shutdown
  102. * shutdown}.
  103. *
  104. * @param nThreads the number of threads in the pool
  105. * @param threadFactory the factory to use when creating new threads
  106. * @return the newly created thread pool
  107. * @throws NullPointerException if threadFactory is null
  108. * @throws IllegalArgumentException if {@code nThreads <= 0}
  109. */
  110. public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
  111. return new ThreadPoolExecutor(nThreads, nThreads,
  112. 0L, TimeUnit.MILLISECONDS,
  113. new LinkedBlockingQueue<Runnable>(),
  114. threadFactory);
  115. }
  116. /**
  117. * Creates an Executor that uses a single worker thread operating
  118. * off an unbounded queue. (Note however that if this single
  119. * thread terminates due to a failure during execution prior to
  120. * shutdown, a new one will take its place if needed to execute
  121. * subsequent tasks.) Tasks are guaranteed to execute
  122. * sequentially, and no more than one task will be active at any
  123. * given time. Unlike the otherwise equivalent
  124. * {@code newFixedThreadPool(1)} the returned executor is
  125. * guaranteed not to be reconfigurable to use additional threads.
  126. *
  127. * @return the newly created single-threaded Executor
  128. */
  129. public static ExecutorService newSingleThreadExecutor() {
  130. return new FinalizableDelegatedExecutorService
  131. (new ThreadPoolExecutor(1, 1,
  132. 0L, TimeUnit.MILLISECONDS,
  133. new LinkedBlockingQueue<Runnable>()));
  134. }
  135. /**
  136. * Creates an Executor that uses a single worker thread operating
  137. * off an unbounded queue, and uses the provided ThreadFactory to
  138. * create a new thread when needed. Unlike the otherwise
  139. * equivalent {@code newFixedThreadPool(1, threadFactory)} the
  140. * returned executor is guaranteed not to be reconfigurable to use
  141. * additional threads.
  142. *
  143. * @param threadFactory the factory to use when creating new
  144. * threads
  145. *
  146. * @return the newly created single-threaded Executor
  147. * @throws NullPointerException if threadFactory is null
  148. */
  149. public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
  150. return new FinalizableDelegatedExecutorService
  151. (new ThreadPoolExecutor(1, 1,
  152. 0L, TimeUnit.MILLISECONDS,
  153. new LinkedBlockingQueue<Runnable>(),
  154. threadFactory));
  155. }
  156. /**
  157. * Creates a thread pool that creates new threads as needed, but
  158. * will reuse previously constructed threads when they are
  159. * available. These pools will typically improve the performance
  160. * of programs that execute many short-lived asynchronous tasks.
  161. * Calls to {@code execute} will reuse previously constructed
  162. * threads if available. If no existing thread is available, a new
  163. * thread will be created and added to the pool. Threads that have
  164. * not been used for sixty seconds are terminated and removed from
  165. * the cache. Thus, a pool that remains idle for long enough will
  166. * not consume any resources. Note that pools with similar
  167. * properties but different details (for example, timeout parameters)
  168. * may be created using {@link ThreadPoolExecutor} constructors.
  169. *
  170. * @return the newly created thread pool
  171. */
  172. public static ExecutorService newCachedThreadPool() {
  173. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
  174. 60L, TimeUnit.SECONDS,
  175. new SynchronousQueue<Runnable>());
  176. }
  177. /**
  178. * Creates a thread pool that creates new threads as needed, but
  179. * will reuse previously constructed threads when they are
  180. * available, and uses the provided
  181. * ThreadFactory to create new threads when needed.
  182. * @param threadFactory the factory to use when creating new threads
  183. * @return the newly created thread pool
  184. * @throws NullPointerException if threadFactory is null
  185. */
  186. public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
  187. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
  188. 60L, TimeUnit.SECONDS,
  189. new SynchronousQueue<Runnable>(),
  190. threadFactory);
  191. }
  192. /**
  193. * Creates a single-threaded executor that can schedule commands
  194. * to run after a given delay, or to execute periodically.
  195. * (Note however that if this single
  196. * thread terminates due to a failure during execution prior to
  197. * shutdown, a new one will take its place if needed to execute
  198. * subsequent tasks.) Tasks are guaranteed to execute
  199. * sequentially, and no more than one task will be active at any
  200. * given time. Unlike the otherwise equivalent
  201. * {@code newScheduledThreadPool(1)} the returned executor is
  202. * guaranteed not to be reconfigurable to use additional threads.
  203. * @return the newly created scheduled executor
  204. */
  205. public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
  206. return new DelegatedScheduledExecutorService
  207. (new ScheduledThreadPoolExecutor(1));
  208. }
  209. /**
  210. * Creates a single-threaded executor that can schedule commands
  211. * to run after a given delay, or to execute periodically. (Note
  212. * however that if this single thread terminates due to a failure
  213. * during execution prior to shutdown, a new one will take its
  214. * place if needed to execute subsequent tasks.) Tasks are
  215. * guaranteed to execute sequentially, and no more than one task
  216. * will be active at any given time. Unlike the otherwise
  217. * equivalent {@code newScheduledThreadPool(1, threadFactory)}
  218. * the returned executor is guaranteed not to be reconfigurable to
  219. * use additional threads.
  220. * @param threadFactory the factory to use when creating new
  221. * threads
  222. * @return a newly created scheduled executor
  223. * @throws NullPointerException if threadFactory is null
  224. */
  225. public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
  226. return new DelegatedScheduledExecutorService
  227. (new ScheduledThreadPoolExecutor(1, threadFactory));
  228. }
  229. /**
  230. * Creates a thread pool that can schedule commands to run after a
  231. * given delay, or to execute periodically.
  232. * @param corePoolSize the number of threads to keep in the pool,
  233. * even if they are idle
  234. * @return a newly created scheduled thread pool
  235. * @throws IllegalArgumentException if {@code corePoolSize < 0}
  236. */
  237. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
  238. return new ScheduledThreadPoolExecutor(corePoolSize);
  239. }
  240. /**
  241. * Creates a thread pool that can schedule commands to run after a
  242. * given delay, or to execute periodically.
  243. * @param corePoolSize the number of threads to keep in the pool,
  244. * even if they are idle
  245. * @param threadFactory the factory to use when the executor
  246. * creates a new thread
  247. * @return a newly created scheduled thread pool
  248. * @throws IllegalArgumentException if {@code corePoolSize < 0}
  249. * @throws NullPointerException if threadFactory is null
  250. */
  251. public static ScheduledExecutorService newScheduledThreadPool(
  252. int corePoolSize, ThreadFactory threadFactory) {
  253. return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
  254. }
  255. /**
  256. * Returns an object that delegates all defined {@link
  257. * ExecutorService} methods to the given executor, but not any
  258. * other methods that might otherwise be accessible using
  259. * casts. This provides a way to safely "freeze" configuration and
  260. * disallow tuning of a given concrete implementation.
  261. * @param executor the underlying implementation
  262. * @return an {@code ExecutorService} instance
  263. * @throws NullPointerException if executor null
  264. */
  265. public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
  266. if (executor == null)
  267. throw new NullPointerException();
  268. return new DelegatedExecutorService(executor);
  269. }
  270. /**
  271. * Returns an object that delegates all defined {@link
  272. * ScheduledExecutorService} methods to the given executor, but
  273. * not any other methods that might otherwise be accessible using
  274. * casts. This provides a way to safely "freeze" configuration and
  275. * disallow tuning of a given concrete implementation.
  276. * @param executor the underlying implementation
  277. * @return a {@code ScheduledExecutorService} instance
  278. * @throws NullPointerException if executor null
  279. */
  280. public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
  281. if (executor == null)
  282. throw new NullPointerException();
  283. return new DelegatedScheduledExecutorService(executor);
  284. }
  285. /**
  286. * Returns a default thread factory used to create new threads.
  287. * This factory creates all new threads used by an Executor in the
  288. * same {@link ThreadGroup}. If there is a {@link
  289. * java.lang.SecurityManager}, it uses the group of {@link
  290. * System#getSecurityManager}, else the group of the thread
  291. * invoking this {@code defaultThreadFactory} method. Each new
  292. * thread is created as a non-daemon thread with priority set to
  293. * the smaller of {@code Thread.NORM_PRIORITY} and the maximum
  294. * priority permitted in the thread group. New threads have names
  295. * accessible via {@link Thread#getName} of
  296. * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
  297. * number of this factory, and <em>M</em> is the sequence number
  298. * of the thread created by this factory.
  299. * @return a thread factory
  300. */
  301. public static ThreadFactory defaultThreadFactory() {
  302. return new DefaultThreadFactory();
  303. }
  304. /**
  305. * Returns a thread factory used to create new threads that
  306. * have the same permissions as the current thread.
  307. * This factory creates threads with the same settings as {@link
  308. * Executors#defaultThreadFactory}, additionally setting the
  309. * AccessControlContext and contextClassLoader of new threads to
  310. * be the same as the thread invoking this
  311. * {@code privilegedThreadFactory} method. A new
  312. * {@code privilegedThreadFactory} can be created within an
  313. * {@link AccessController#doPrivileged AccessController.doPrivileged}
  314. * action setting the current thread's access control context to
  315. * create threads with the selected permission settings holding
  316. * within that action.
  317. *
  318. * <p>Note that while tasks running within such threads will have
  319. * the same access control and class loader settings as the
  320. * current thread, they need not have the same {@link
  321. * java.lang.ThreadLocal} or {@link
  322. * java.lang.InheritableThreadLocal} values. If necessary,
  323. * particular values of thread locals can be set or reset before
  324. * any task runs in {@link ThreadPoolExecutor} subclasses using
  325. * {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}.
  326. * Also, if it is necessary to initialize worker threads to have
  327. * the same InheritableThreadLocal settings as some other
  328. * designated thread, you can create a custom ThreadFactory in
  329. * which that thread waits for and services requests to create
  330. * others that will inherit its values.
  331. *
  332. * @return a thread factory
  333. * @throws AccessControlException if the current access control
  334. * context does not have permission to both get and set context
  335. * class loader
  336. */
  337. public static ThreadFactory privilegedThreadFactory() {
  338. return new PrivilegedThreadFactory();
  339. }
  340. /**
  341. * Returns a {@link Callable} object that, when
  342. * called, runs the given task and returns the given result. This
  343. * can be useful when applying methods requiring a
  344. * {@code Callable} to an otherwise resultless action.
  345. * @param task the task to run
  346. * @param result the result to return
  347. * @param <T> the type of the result
  348. * @return a callable object
  349. * @throws NullPointerException if task null
  350. */
  351. public static <T> Callable<T> callable(Runnable task, T result) {
  352. if (task == null)
  353. throw new NullPointerException();
  354. return new RunnableAdapter<T>(task, result);
  355. }
  356. /**
  357. * Returns a {@link Callable} object that, when
  358. * called, runs the given task and returns {@code null}.
  359. * @param task the task to run
  360. * @return a callable object
  361. * @throws NullPointerException if task null
  362. */
  363. public static Callable<Object> callable(Runnable task) {
  364. if (task == null)
  365. throw new NullPointerException();
  366. return new RunnableAdapter<Object>(task, null);
  367. }
  368. /**
  369. * Returns a {@link Callable} object that, when
  370. * called, runs the given privileged action and returns its result.
  371. * @param action the privileged action to run
  372. * @return a callable object
  373. * @throws NullPointerException if action null
  374. */
  375. public static Callable<Object> callable(final PrivilegedAction<?> action) {
  376. if (action == null)
  377. throw new NullPointerException();
  378. return new Callable<Object>() {
  379. public Object call() { return action.run(); }};
  380. }
  381. /**
  382. * Returns a {@link Callable} object that, when
  383. * called, runs the given privileged exception action and returns
  384. * its result.
  385. * @param action the privileged exception action to run
  386. * @return a callable object
  387. * @throws NullPointerException if action null
  388. */
  389. public static Callable<Object> callable(final PrivilegedExceptionAction<?> action) {
  390. if (action == null)
  391. throw new NullPointerException();
  392. return new Callable<Object>() {
  393. public Object call() throws Exception { return action.run(); }};
  394. }
  395. /**
  396. * Returns a {@link Callable} object that will, when called,
  397. * execute the given {@code callable} under the current access
  398. * control context. This method should normally be invoked within
  399. * an {@link AccessController#doPrivileged AccessController.doPrivileged}
  400. * action to create callables that will, if possible, execute
  401. * under the selected permission settings holding within that
  402. * action; or if not possible, throw an associated {@link
  403. * AccessControlException}.
  404. * @param callable the underlying task
  405. * @param <T> the type of the callable's result
  406. * @return a callable object
  407. * @throws NullPointerException if callable null
  408. */
  409. public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
  410. if (callable == null)
  411. throw new NullPointerException();
  412. return new PrivilegedCallable<T>(callable);
  413. }
  414. /**
  415. * Returns a {@link Callable} object that will, when called,
  416. * execute the given {@code callable} under the current access
  417. * control context, with the current context class loader as the
  418. * context class loader. This method should normally be invoked
  419. * within an
  420. * {@link AccessController#doPrivileged AccessController.doPrivileged}
  421. * action to create callables that will, if possible, execute
  422. * under the selected permission settings holding within that
  423. * action; or if not possible, throw an associated {@link
  424. * AccessControlException}.
  425. *
  426. * @param callable the underlying task
  427. * @param <T> the type of the callable's result
  428. * @return a callable object
  429. * @throws NullPointerException if callable null
  430. * @throws AccessControlException if the current access control
  431. * context does not have permission to both set and get context
  432. * class loader
  433. */
  434. public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
  435. if (callable == null)
  436. throw new NullPointerException();
  437. return new PrivilegedCallableUsingCurrentClassLoader<T>(callable);
  438. }
  439. // Non-public classes supporting the public methods
  440. /**
  441. * A callable that runs given task and returns given result
  442. */
  443. static final class RunnableAdapter<T> implements Callable<T> {
  444. final Runnable task;
  445. final T result;
  446. RunnableAdapter(Runnable task, T result) {
  447. this.task = task;
  448. this.result = result;
  449. }
  450. public T call() {
  451. task.run();
  452. return result;
  453. }
  454. }
  455. /**
  456. * A callable that runs under established access control settings
  457. */
  458. static final class PrivilegedCallable<T> implements Callable<T> {
  459. private final Callable<T> task;
  460. private final AccessControlContext acc;
  461. PrivilegedCallable(Callable<T> task) {
  462. this.task = task;
  463. this.acc = AccessController.getContext();
  464. }
  465. public T call() throws Exception {
  466. try {
  467. return AccessController.doPrivileged(
  468. new PrivilegedExceptionAction<T>() {
  469. public T run() throws Exception {
  470. return task.call();
  471. }
  472. }, acc);
  473. } catch (PrivilegedActionException e) {
  474. throw e.getException();
  475. }
  476. }
  477. }
  478. /**
  479. * A callable that runs under established access control settings and
  480. * current ClassLoader
  481. */
  482. static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
  483. private final Callable<T> task;
  484. private final AccessControlContext acc;
  485. private final ClassLoader ccl;
  486. PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
  487. SecurityManager sm = System.getSecurityManager();
  488. if (sm != null) {
  489. // Calls to getContextClassLoader from this class
  490. // never trigger a security check, but we check
  491. // whether our callers have this permission anyways.
  492. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  493. // Whether setContextClassLoader turns out to be necessary
  494. // or not, we fail fast if permission is not available.
  495. sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  496. }
  497. this.task = task;
  498. this.acc = AccessController.getContext();
  499. this.ccl = Thread.currentThread().getContextClassLoader();
  500. }
  501. public T call() throws Exception {
  502. try {
  503. return AccessController.doPrivileged(
  504. new PrivilegedExceptionAction<T>() {
  505. public T run() throws Exception {
  506. Thread t = Thread.currentThread();
  507. ClassLoader cl = t.getContextClassLoader();
  508. if (ccl == cl) {
  509. return task.call();
  510. } else {
  511. t.setContextClassLoader(ccl);
  512. try {
  513. return task.call();
  514. } finally {
  515. t.setContextClassLoader(cl);
  516. }
  517. }
  518. }
  519. }, acc);
  520. } catch (PrivilegedActionException e) {
  521. throw e.getException();
  522. }
  523. }
  524. }
  525. /**
  526. * The default thread factory
  527. */
  528. static class DefaultThreadFactory implements ThreadFactory {
  529. private static final AtomicInteger poolNumber = new AtomicInteger(1);
  530. private final ThreadGroup group;
  531. private final AtomicInteger threadNumber = new AtomicInteger(1);
  532. private final String namePrefix;
  533. DefaultThreadFactory() {
  534. SecurityManager s = System.getSecurityManager();
  535. group = (s != null) ? s.getThreadGroup() :
  536. Thread.currentThread().getThreadGroup();
  537. namePrefix = "pool-" +
  538. poolNumber.getAndIncrement() +
  539. "-thread-";
  540. }
  541. public Thread newThread(Runnable r) {
  542. Thread t = new Thread(group, r,
  543. namePrefix + threadNumber.getAndIncrement(),
  544. 0);
  545. if (t.isDaemon())
  546. t.setDaemon(false);
  547. if (t.getPriority() != Thread.NORM_PRIORITY)
  548. t.setPriority(Thread.NORM_PRIORITY);
  549. return t;
  550. }
  551. }
  552. /**
  553. * Thread factory capturing access control context and class loader
  554. */
  555. static class PrivilegedThreadFactory extends DefaultThreadFactory {
  556. private final AccessControlContext acc;
  557. private final ClassLoader ccl;
  558. PrivilegedThreadFactory() {
  559. super();
  560. SecurityManager sm = System.getSecurityManager();
  561. if (sm != null) {
  562. // Calls to getContextClassLoader from this class
  563. // never trigger a security check, but we check
  564. // whether our callers have this permission anyways.
  565. sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
  566. // Fail fast
  567. sm.checkPermission(new RuntimePermission("setContextClassLoader"));
  568. }
  569. this.acc = AccessController.getContext();
  570. this.ccl = Thread.currentThread().getContextClassLoader();
  571. }
  572. public Thread newThread(final Runnable r) {
  573. return super.newThread(new Runnable() {
  574. public void run() {
  575. AccessController.doPrivileged(new PrivilegedAction<Void>() {
  576. public Void run() {
  577. Thread.currentThread().setContextClassLoader(ccl);
  578. r.run();
  579. return null;
  580. }
  581. }, acc);
  582. }
  583. });
  584. }
  585. }
  586. /**
  587. * A wrapper class that exposes only the ExecutorService methods
  588. * of an ExecutorService implementation.
  589. */
  590. static class DelegatedExecutorService extends AbstractExecutorService {
  591. private final ExecutorService e;
  592. DelegatedExecutorService(ExecutorService executor) { e = executor; }
  593. public void execute(Runnable command) { e.execute(command); }
  594. public void shutdown() { e.shutdown(); }
  595. public List<Runnable> shutdownNow() { return e.shutdownNow(); }
  596. public boolean isShutdown() { return e.isShutdown(); }
  597. public boolean isTerminated() { return e.isTerminated(); }
  598. public boolean awaitTermination(long timeout, TimeUnit unit)
  599. throws InterruptedException {
  600. return e.awaitTermination(timeout, unit);
  601. }
  602. public Future<?> submit(Runnable task) {
  603. return e.submit(task);
  604. }
  605. public <T> Future<T> submit(Callable<T> task) {
  606. return e.submit(task);
  607. }
  608. public <T> Future<T> submit(Runnable task, T result) {
  609. return e.submit(task, result);
  610. }
  611. public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
  612. throws InterruptedException {
  613. return e.invokeAll(tasks);
  614. }
  615. public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
  616. long timeout, TimeUnit unit)
  617. throws InterruptedException {
  618. return e.invokeAll(tasks, timeout, unit);
  619. }
  620. public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
  621. throws InterruptedException, ExecutionException {
  622. return e.invokeAny(tasks);
  623. }
  624. public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
  625. long timeout, TimeUnit unit)
  626. throws InterruptedException, ExecutionException, TimeoutException {
  627. return e.invokeAny(tasks, timeout, unit);
  628. }
  629. }
  630. static class FinalizableDelegatedExecutorService
  631. extends DelegatedExecutorService {
  632. FinalizableDelegatedExecutorService(ExecutorService executor) {
  633. super(executor);
  634. }
  635. protected void finalize() {
  636. super.shutdown();
  637. }
  638. }
  639. /**
  640. * A wrapper class that exposes only the ScheduledExecutorService
  641. * methods of a ScheduledExecutorService implementation.
  642. */
  643. static class DelegatedScheduledExecutorService
  644. extends DelegatedExecutorService
  645. implements ScheduledExecutorService {
  646. private final ScheduledExecutorService e;
  647. DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
  648. super(executor);
  649. e = executor;
  650. }
  651. public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
  652. return e.schedule(command, delay, unit);
  653. }
  654. public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
  655. return e.schedule(callable, delay, unit);
  656. }
  657. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
  658. return e.scheduleAtFixedRate(command, initialDelay, period, unit);
  659. }
  660. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
  661. return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
  662. }
  663. }
  664. /** Cannot instantiate. */
  665. private Executors() {}
  666. }

 

队列与线程池结合

以阿里云OSS文件存储为例:

  1. package com.forestar.aliyun.service.oss.queue;
  2. import com.forestar.aliyun.service.oss.bean.FileInfo;
  3. import com.forestar.aliyun.service.oss.tds.OssHttpService;
  4. import lombok.extern.slf4j.Slf4j;
  5. import java.util.concurrent.ConcurrentLinkedQueue;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.atomic.AtomicInteger;
  9. import java.util.concurrent.atomic.AtomicLong;
  10. /**
  11. * @Copyright: 2019-2021
  12. * @FileName: FileUploadQueue.java
  13. * @Author: PJL
  14. * @Date: 2020/12/3 10:35
  15. * @Description: 文件上传队列
  16. */
  17. @Slf4j
  18. public class FileUploadQueue {
  19. private ConcurrentLinkedQueue<FileInfo> queue = new ConcurrentLinkedQueue<>();
  20. private AtomicLong total = new AtomicLong(0);
  21. private AtomicLong completed = new AtomicLong(0);
  22. private AtomicInteger exeCount = new AtomicInteger(0);
  23. private ExecutorService executorService;
  24. private OssHttpService ossHttpService;
  25. private Boolean started = false;
  26. private int poolSize;
  27. /**
  28. * 文件上传队列初始化
  29. *
  30. * @param ossHttpService
  31. * @param executorPoolSize
  32. * @param startConsumer
  33. */
  34. public FileUploadQueue(OssHttpService ossHttpService, int executorPoolSize, boolean startConsumer) {
  35. this.poolSize = executorPoolSize;
  36. this.ossHttpService = ossHttpService;
  37. this.executorService = Executors.newWorkStealingPool(this.poolSize);
  38. if (startConsumer) {
  39. this.start();
  40. }
  41. }
  42. /**
  43. * 文件入队列
  44. *
  45. * @param fileInfo
  46. */
  47. public Long enqueue(FileInfo fileInfo) {
  48. queue.add(fileInfo);
  49. return total.incrementAndGet();
  50. }
  51. /**
  52. * 空闲判断
  53. *
  54. * @return
  55. */
  56. public Boolean isUnFull() {
  57. return exeCount.get() < poolSize;
  58. }
  59. /**
  60. * 空闲判断
  61. *
  62. * @return
  63. */
  64. public Boolean isBusy() {
  65. return exeCount.get() > 5 && isUnFull();
  66. }
  67. /**
  68. * 空闲判断
  69. *
  70. * @return
  71. */
  72. public Boolean isIdle() {
  73. return exeCount.get() <= 5;
  74. }
  75. /**
  76. * 开启消费线程
  77. */
  78. public void start() {
  79. if (!started) {
  80. new Thread(() -> {
  81. while (true) {
  82. try {
  83. int count = queue.size();
  84. // 线程池消费
  85. if (count > 0 && isUnFull()) {
  86. consumer();
  87. }
  88. // 忙碌延长休眠
  89. if (count > 0 && isBusy()) {
  90. Thread.sleep(100);
  91. }
  92. // 空闲缩短休眠
  93. else if (count > 0 && isIdle()) {
  94. Thread.sleep(50);
  95. }else{
  96. Thread.sleep(1000);
  97. }
  98. } catch (InterruptedException e) {
  99. e.printStackTrace();
  100. }
  101. }
  102. }).start();
  103. started = true;
  104. }
  105. }
  106. /**
  107. * 执行业务处理
  108. */
  109. private void consumer() {
  110. FileInfo fileInfo = queue.poll();
  111. if (null != fileInfo) {
  112. // 增加线程占用数量
  113. exeCount.incrementAndGet();
  114. // 提交执行任务
  115. executorService.submit(() -> {
  116. // 处理业务数据
  117. ossHttpService.syncToAliyunOss(fileInfo);
  118. // 执行个数增加
  119. completed.incrementAndGet();
  120. // 线程池占用减少
  121. if (exeCount.get() > 0) {
  122. exeCount.decrementAndGet();
  123. }
  124. // 打印处理进度
  125. log.info("===队列消费进度==={}/{}", completed.get(), total.get());
  126. // 处理完成通知
  127. if (completed.get() == total.get()) {
  128. log.info("=====================所有文件上传完成!=======================");
  129. }
  130. });
  131. }
  132. }
  133. }

最终我们得到类似下面的效果输出:

  1. 2020-12-03 12:38:08.802 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : >>>开始解析....D:/TDSpath/list.txt
  2. 2020-12-03 12:38:08.804 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : httpUrl = http://remote_host/upload/eventAttach/eventpic/original/202007/20200711/05290729-bf44-41c6-8da7-44251e131d15.jpg , objectName = /upload/eventAttach/eventpic/original/202007/20200711/05290729-bf44-41c6-8da7-44251e131d15.jpg
  3. 2020-12-03 12:38:08.804 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : ==文件队列长度== size =1
  4. 2020-12-03 12:38:08.805 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : httpUrl = http://remote_host/upload/eventAttach/eventpic/thumb/202007/20200711/05290729-bf44-41c6-8da7-44251e131d15.jpg , objectName = /upload/eventAttach/eventpic/thumb/202007/20200711/05290729-bf44-41c6-8da7-44251e131d15.jpg
  5. 2020-12-03 12:38:08.805 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : ==文件队列长度== size =2
  6. 2020-12-03 12:38:08.805 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : httpUrl = http://remote_host/upload/eventAttach/eventpic/original/202007/20200711/15d1724a-a969-41f7-abe8-171904a746da.jpg , objectName = /upload/eventAttach/eventpic/original/202007/20200711/15d1724a-a969-41f7-abe8-171904a746da.jpg
  7. 2020-12-03 12:38:08.805 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : ==文件队列长度== size =3
  8. 2020-12-03 12:38:08.806 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : httpUrl = http://remote_host/upload/eventAttach/eventpic/thumb/202007/20200711/15d1724a-a969-41f7-abe8-171904a746da.jpg , objectName = /upload/eventAttach/eventpic/thumb/202007/20200711/15d1724a-a969-41f7-abe8-171904a746da.jpg
  9. 2020-12-03 12:38:08.807 INFO 9792 --- [pool-3-thread-1] c.f.a.service.oss.tds.OssHttpService : ==文件队列长度== size =4
  10. 2020-12-03 12:38:09.805 INFO 9792 --- [Pool-3-worker-9] c.f.a.service.oss.queue.FileUploadQueue : ===队列消费进度===1/4
  11. 2020-12-03 12:38:09.856 INFO 9792 --- [Pool-3-worker-9] c.f.a.service.oss.queue.FileUploadQueue : ===队列消费进度===2/4
  12. 2020-12-03 12:38:09.907 INFO 9792 --- [Pool-3-worker-9] c.f.a.service.oss.queue.FileUploadQueue : ===队列消费进度===3/4
  13. 2020-12-03 12:38:09.957 INFO 9792 --- [Pool-3-worker-9] c.f.a.service.oss.queue.FileUploadQueue : ===队列消费进度===4/4
  14. 2020-12-03 12:38:09.957 INFO 9792 --- [Pool-3-worker-9] c.f.a.service.oss.queue.FileUploadQueue : =====================所有文件上传完成!=======================

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载