Java Concurrency programming: synchronizing containersTo facilitate the writing of thread-safe programs, Java provides threading and concurrency tools such as synchronization containers, concurrent containers, blocking queues, synchronizer (such as Countdownlatch). Today we are going to discuss the synchronization cont
, resulting in multi-tasking is the illusion of parallel operationIn fact, if there is only one CPU in the system, and the use of multi-threaded tasks, then these tasks in the real environment can not be real parallel. After all, a CPU can only run one instruction at a time, in which case multithreading is concurrent, not parallel; Real parallelism can only occur in multi-CPU systems Critical section A critical section is used to represent public resources, or shared data, that can be used
Java does not provide any mechanism to safely terminate a thread (although the Thread.stop and suspend methods provide such a mechanism, but because of a flaw, you should avoid usingInterrupt: A collaboration mechanism that enables one thread to terminate the current work of another threadstopping immediately causes the shared data structure to be in an inconsistent state , and when it needs to be stopped, an interrupt request is made, and the thread
subtask thread), but cannot be performed until the blocking thread is freed.The following example shows the use of Cyclicbarrier. 1 Import java.util.concurrent.BrokenBarrierException; 2 Import Java.util.concurrent.CyclicBarrier; 3 4/** 5 * @author Bridge 6 */7 public class Cyclicbarriertest {8 9 public static void Main (string[] args) {1 0 int N = 4;11 Cyclicbarrier cyclicbarrier = new Cyclicbarrier (n); (int i = 0; i Execution resultsthread-1 Ready!thread-3 Ready! thread-2 Ready! thread-0 Re
Built-in lock and built-in condition queue together, a simple application is to create a blocking bounded buffer, Java and the blockingqueue of the contract is a blocking bounded queue implemented with lock and explicit conditional queue. Summarize the principles of built-in locks and built-in conditions, where we can implement a simple, blocking cache in another way. The source code is as follows:First, create an abstract bounded cache class Abounded
between Takeindex and putindex what to do? At this point, starting from the deleted position I, all the element positions after I are moved to "left" one bit until putindex. The end result is that all elements of the delete position "back" a position, while the Putindex also backs up a position.Listing 3 Deleting any one element
public boolean remove (Object o) {if (o = = null) return false;Final e[] items = this.items;Final Reentrantlock lock = This.lock;Lock.lock ();try {int i = Takeindex
the thread pool ends.
IsTerminating () describes the shutdown and stop two states.
IsShutDown () describes the non-running state, which is shutdown/stop/terminated three states.
Figure 1The API for the thread pool is as follows:Figure 2where Shutdownnow () returns a list of tasks that have entered the queue but have not yet been executed. Awaittermination describes the time it takes to wait for the thread pool to shut down, and a timeout exception will be thrown if the wait time th
expansion, Because there is no need to replicate the original queue, it may be more efficient in some cases.It is also important to note that both implementations are not thread-safe and are therefore only suitable for use in single-threaded environments, and the Linkedblockingdeque described in the following sections are thread-safe and deque. In fact, it should be the most powerful queue implementation, and of course it might be a bit more complicated to implement.In layman's
concurrent containers to improve the performance of the synchronization container.
Concurrenthashmap instead of HashMap, its internal through the segmented lock, to improve the efficiency of concurrent reading and writing
Copyonwritearraylist, the underlying array is duplicated whenever the container is modified, so there is some overhead, so only if the iteration is much more than the modify operation, you should use the
Executor frameProvides a standard when a method decoupl
JDK command reflow, see the previous CSDN blog: Java memory model and command reflowLazy: Use static inner classpublic class Singleton {private Static Class Lazyholder {private static final Singleton INSTANCE = new Singleton ();}Private Singleton () {}public static final Singleton getinstance () {return lazyholder.instance;}}This method not only solves the synchronization problem, but also solves the tedious problem. It is recommended to use the rewr
Visibility: Multiple threads can share access and manipulate the same variables, but one thread changes to a shared variable, and the other thread doesn't have to see it right away, or even never see it. Because it involves registers and cache levels.Solution:
Using the volatile keyword
Using the Synchronized keyword
5, synchronizedSynchronized can be used to modify an instance method of a class (protect this), a static method (a protected class object), a code block (arbitrar
;set_safepoint_visible (TRUE);
Threadservice::add_thread (P, daemon);
//Possible GC point.
Events::log (P, "Thread added:" Intptr_format, p);
}
(2) After the thread executes, it will clean itself out of the thread list (source location: Threads::remove (this)); So just determine if thread 1 is present in the thread list and judge the source code (located atbiasedLocking.cpp) are as follow
Futuretask implements the runnable and future interfaces and is an asynchronous task that can be canceled. This class provides a basic implementation of the future, taking advantage of the method of starting and canceling the calculation, the method of querying whether the calculation is complete, and the method of obtaining the result of the calculation. The result is only available when the calculation is complete, and if the calculation is not completed, the Get method is blocked. Once the ca
Volatile provides a weak synchronization mechanism to ensure that variable updates are notified to other threads. Volatile variables are not cached in registers or invisible to other processors, so the most recent write value is always returned when reading a volatile variable. You can imagine the following semantics, but volatile is a more lightweight synchronization mechanism.volatile can only ensure visibility, but it does not guarantee atomicity. In other words, it cannot be used in composit
{System.out.println (id +"th people Wait"); Barrier.await ();//Everyone waits for the last thread to arrive}Catch(Interruptedexception | Brokenbarrierexception e) {//TODO auto-generated catch blockE.printstacktrace (); } }} Public class testcyclicbarrier { Public Static void Main(string[] args) {intnum =Ten; Cyclicbarrier barrier =NewCyclicbarrier (NUM,NewRunnable () {@Override Public void Run() {//TODO auto-generated method stubSystem.out.println ("Go on together!"); }
)) { if (runState != RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } //如果线程池不处于运行中或任务无法放入队列,并且当前线程数量小于最大允许的线程数量,则创建一个线程执行任务。 else if (!addIfUnderMaximumPoolSize(command)) //抛出RejectedExecutionException异常 reject(command); // is shutdown or saturated }} When the thread pool creates threads, the thread is encapsulated as a worker thread worker,worker the tasks in the work queue are executed indefinitely after the
Status of Threads: New, Runnable, Blocked, waiting, Timed waiting, Terminated1. RUNNABLE, corresponding to the "Ready" and "running" states, that is, in the ready and running state of the thread in the Java.lang.Thread is displayed as "RUNNABLE"2. BLOCKED, corresponding to the "blocking" state, this thread needs to obtain a lock to continue execution, and this lock is currently held by other threads, so entered a passive wait state, until the lock was grabbed, will again enter the "Ready" state3
between thread and runnablethe same point of thread and Runnable : "Multithreading is the way to implement."different points of Thread and Runnable :Thread is a class, and runnable is an interface; the thread itself is the class that implements the Runnable interface. We know that "a class can have only one parent class, but it can implement multiple interfaces," So runnable has better extensibility.In addition, runnable can also be used for "resource sharing". That is, multiple threads are bui
This article is a summary of the study of the article on the network, thank you for your selfless sharing.Read-write locks are important for the use of write locks, with only one entry.Here is an example of a read-write lock usePackage Chapter2;import Java.util.concurrent.locks.readwritelock;import Java.util.concurrent.locks.reentrantreadwritelock;public class Pricesinfo {private int price1;private int price2; Private Readwritelock lock;public Pricesinfo () {Price1 = 1;price2 = 1;lock = new Reen
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.