Execution Program
Interface.Executor
Is a simple standardized interface used to define custom subsystems similar to threads, including thread pools, asynchronous Io, and lightweight task frameworks. Depending on the specific executor class used, it is possible that in the newly created thread, the existing task execution thread, orExecute ()And may be executed in sequence or concurrently.ExecutorService
Provides multiple complete asynchronous task execution frameworks. Executorservice manages the queuing and arrangement of tasks and allows controlled shutdown.ScheduledExecutorService
Added support for delayed and scheduled task execution for subinterfaces and related interfaces. Executorservice provides a method for arranging asynchronous execution.Callable
Any function. The result is similarRunnable
.Future
Returns the result of the function, allows you to determine whether the execution is complete, and provides a method to cancel the execution.RunnableFuture
YesRunMethod future,RunThe result is set when the method is executed.
.ClassThreadPoolExecutor
AndScheduledThreadPoolExecutor
Provides an adjustable and flexible thread pool.Executors
Class provides common types and configuration factory methods for most executors, and several utility methods for using them. Other executor-based utilities includeFutureTask
, Which provides common extensible implementations of the future, andExecutorCompletionService
It helps coordinate the processing of asynchronous task groups.
Queue
Java. util. ConcurrentConcurrentLinkedQueue
Class provides efficient, scalable, and thread-safe non-blocking FIFO queues. The five implementations in Java. util. Concurrent support extendedBlockingQueue
Interface, which defines the blocking versions of put and take:LinkedBlockingQueue
,ArrayBlockingQueue
,SynchronousQueue
,PriorityBlockingQueue
AndDelayQueue
. These classes cover most of the common use contexts of producer-user, message passing, parallel task execution, and related concurrency design.BlockingDeque
Interface ExtensionBlockingqueueTo support FIFO and LIFO (stack-based) operations.LinkedBlockingDeque
Class provides an implementation.
Timing
TimeUnit
Class provides multiple granularities (including nanoseconds) for specifying and controlling timeout-based operations ). In addition to uncertain waiting, most classes in this package also contain timeout-based operations. In all cases where timeout is used, timeout specifies the minimum time that the method should wait before timeout. After the timeout occurs, the implementation will "try its best" to detect the timeout. However, it may take an uncertain time between the detection timeout and the actual execution thread again after the timeout. All methods that accept parameters over time are considered as not waiting for values smaller than or equal to 0. To "always" wait, you can useLong. max_valueValue.
Synx
The four types can help implement common dedicated synchronization statements.Semaphore
Is a classic concurrency tool.CountDownLatch
It is an extremely simple but extremely commonly used utility used to block execution before a certain number of signals, events, or conditions are maintained.CyclicBarrier
It is a retriable multi-channel synchronization point, which is useful in some parallel programming styles.Exchanger
Two threads are allowed to exchange objects at collection points, which is useful in Multi-pipeline design.
Concurrent collection
In addition to queues, this package also provides collection implementation designed for multi-threaded context:ConcurrentHashMap
,ConcurrentSkipListMap
,ConcurrentSkipListSet
,CopyOnWriteArrayList
AndCopyOnWriteArraySet
. When many threads are expected to access a given collection,ConcurrenthashmapUsually better than synchronousHashmap,ConcurrentskiplistmapUsually better than synchronousTreemap. When the expected reading and traversal are much larger than the number of list updates,CopyonwritearraylistBetter than synchronousArraylist.
The "concurrent" prefix used with some classes in this package is short, indicating that it is different from a similar "synchronization" class. For example,Java. util. hashtableAndCollections. synchronizedmap (New hashmap ())Yes,ConcurrentHashMap
It is "concurrent ". Concurrent collection is thread-safe, but is not managed by a single exclusive lock. In this particular case, concurrenthashmap can securely allow any number of concurrent reads and write with an adjustable number. When you need to use a single lock to prohibit all access to the collection, the "synchronization" class is very useful at the cost of poor scalability. In other cases where multiple threads are expected to access the public collection, the "concurrent" version is usually better. If the collection is not shared, or the collection is accessible only when other locks are kept, non-synchronous collection is better.
Most concurrent collection implementations (including most Queue) are different from conventional java. util conventions because their iterators provideWeak ConsistentInstead of traversing a fast failure. The Weak Consistent iterator is thread-safe, but there is no need to freeze the collection during iteration, so it does not necessarily reflect all updates since the iterator was created.
Memory consistency attribute
Java language specification chapter 17th definesHappen-beforeLink. Only write operationsHappen-beforeRead Operations ensure that the results written by one thread are visible to the other.synchronized
Andvolatile
StructureHappen-beforeLink,Thread.start()
AndThread.join()
Method FormationHappen-beforeLink. Especially:
- Every operation in the threadHappen-beforeEach operation in the thread that will be passed in program order later.
- An unlock Monitor (
synchronized
Blocking or method Exit)Happen-beforeEach subsequent lock of the same Monitor (synchronized
Blocking or method access ). And becauseHappen-beforeLinks can be passed, so all operations on the previous thread are unlocked.Happen-beforeLock all subsequent operations of any thread of the monitor.
- Write
volatile
FieldHappen-beforeEach subsequent read of the same field.volatile
The reading and writing of fields have similar memory consistency effects with the entry and exit of the monitor,NoMutex lock is required.
- Call on Thread
start
Happen-beforeAny thread in the started thread.
- All operations in the threadHappen-beforeFrom this thread
join
Any other threads returned successfully.
java.util.concurrent
And its sub-packages extend these guarantees for higher-level synchronization. Especially:
- Operations before putting an object into any concurrent collection in a threadHappen-beforeSubsequent operations to access or remove this element from collections in another thread.
- Thread direction
Executor
SubmitRunnable
Previous operationsHappen-beforeThe execution starts. The same appliesExecutorService
SubmitCallables
.
- Asynchronous computing
Future
Indicates the action taken.Happen-beforeAnother threadFuture.get()
Subsequent operations for obtaining results.
- "Release" synchronous storage method (such
Lock.unlock
,Semaphore.release
AndCountDownLatch.countDown
) Previous operationsHappen-beforeIn the other line, the same synchronization storage object is successfully "obtained" (for exampleLock.lock
,Semaphore.acquire
,Condition.await
AndCountDownLatch.await
.
- For
Exchanger
Each Thread Pair of the object is successfully exchanged.exchange()
Previous operationsHappen-beforeCorrespondsexchange()
Subsequent operations.
- Call
CyclicBarrier.await
Previous operationsHappen-beforeOperations performed by barrier operations and Barrier operationsHappen-beforeCorrespondsawait
Subsequent operations are returned successfully.