publicenumState{ /** * Thread state for a thread which has not yet started. */ NEW,
/** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE,
/** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED,
/** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING,
/** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING,
/** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
/** * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ publicReentrantLock(){ sync = new NonfairSync(); } /** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ publicReentrantLock(boolean fair){ sync = fair ? new FairSync() : new NonfairSync(); }
publicclassTest{ publicstaticvoidmain(String[] args){ List<String> list = Collections.synchronizedList(new ArrayList<>()); for(int i = 1; i <= 20; i++) { new Thread(()->{ list.add("1111"); System.out.println(list); },String.valueOf(i)).start(); } } }
使用CopyOnWriteArrayList实现类。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest{ publicstaticvoidmain(String[] args){ List<String> list = new CopyOnWriteArrayList<>(); for(int i = 1; i <= 20; i++) { new Thread(()->{ list.add("1111"); System.out.println(list); },String.valueOf(i)).start(); } } }
Set
HashSet也和ArrayList一样不安全,所以需要进行一些操作。
使用Collections工具类将HashSet转换成安全的实现类。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest{ publicstaticvoidmain(String[] args){ Set<String> set = Collections.synchronizedSet(new HashSet<>()); for(int i = 1; i <= 20; i++) { new Thread(()->{ set.add(UUID.randomUUID().toString()); System.out.println(set); },String.valueOf(i)).start(); } } }
使用CopyOnWriteArrayList实现类。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest{ publicstaticvoidmain(String[] args){ Set<String> set = new CopyOnWriteArraySet<>(); for(int i = 1; i <= 20; i++) { new Thread(()->{ set.add(UUID.randomUUID().toString()); System.out.println(set); },String.valueOf(i)).start(); } } }
Map
使用Collections工具类将HashMap转换成安全的实现类。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest{ publicstaticvoidmain(String[] args){ Map<String,String> map = Collections.synchronizedMap(new HashMap<>()); for(int i = 1; i <= 20; i++) { new Thread(()->{ map.put(Thread.currentThread().getName(),UUID.randomUUID().toString()); System.out.println(map); },String.valueOf(i)).start(); } } }
使用ConcurrentHashMap实现类。
1 2 3 4 5 6 7 8 9 10 11
publicclassTest{ publicstaticvoidmain(String[] args){ Map<String,String> map = new ConcurrentHashMap<>(); for(int i = 1; i <= 20; i++) { new Thread(()->{ map.put(Thread.currentThread().getName(),UUID.randomUUID().toString()); System.out.println(map); },String.valueOf(i)).start(); } } }
* <ol> * * <li> In the default {@link ThreadPoolExecutor.AbortPolicy}, the * handler throws a runtime {@link RejectedExecutionException} upon * rejection. </li> * * <li> In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread * that invokes {@code execute} itself runs the task. This provides a * simple feedback control mechanism that will slow down the rate that * new tasks are submitted. </li> * * <li> In {@link ThreadPoolExecutor.DiscardPolicy}, a task that * cannot be executed is simply dropped. </li> * * <li>In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the * executor is not shut down, the task at the head of the work queue * is dropped, and then execution is retried(which can fail again, * causing this to be repeated.) </li> * * </ol>
AbortPolicy 丢弃任务并抛出RejectedExecutionException异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicstaticclassAbortPolicyimplementsRejectedExecutionHandler{ /** * Creates an {@code AbortPolicy}. */ publicAbortPolicy(){ }
/** * Always throws RejectedExecutionException. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task * @throws RejectedExecutionException always */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ thrownew RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString()); } }
这是线程池默认的拒绝策略,在类中也可以看到。
1 2
privatestaticfinal RejectedExecutionHandler defaultHandler = new AbortPolicy();
CallerRunsPolicy
调用任务的run()方法绕过线程池直接执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicstaticclassCallerRunsPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code CallerRunsPolicy}. */ publicCallerRunsPolicy(){ }
/** * Executes task r in the caller's thread, unless the executor * has been shut down, in which case the task is discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ if (!e.isShutdown()) { r.run(); } } }
DiscardPolicy 丢弃任务,但是不会抛出异常,这是不推荐使用的拒绝策略。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicstaticclassDiscardPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code DiscardPolicy}. */ publicDiscardPolicy(){ }
/** * Does nothing, which has the effect of discarding task r. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ } }
publicstaticclassDiscardOldestPolicyimplementsRejectedExecutionHandler{ /** * Creates a {@code DiscardOldestPolicy} for the given executor. */ publicDiscardOldestPolicy(){ }
/** * Obtains and ignores the next task that the executor * would otherwise execute, if one is immediately available, * and then retries execution of task r, unless the executor * is shut down, in which case task r is instead discarded. * * @param r the runnable task requested to be executed * @param e the executor attempting to execute this task */ publicvoidrejectedExecution(Runnable r, ThreadPoolExecutor e){ if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } }