Before JDK 1.5, referring to concurrency, Java programmers generally think of wait (), notify (), synchronized keyword, etc., but in addition to consider competing resources, deadlock, resource fairness and other issues, often need to consider performance issues, In some business scenarios are often more complex, which gives the Java coder the problem. The concurrent package from JDK 1.5 helped us solve a lot of problems.
Concurrent package contains a few more commonly used concurrent modules, this series, LZ and everyone together to learn each module, let's go!
Basic usage of thread pool
There are three common thread pool instantiation methods in the general concurrency package, in the Executors factory class.
- newfixedthreadpool (int size):
Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue (linkedblockingqueue) manner. Threads at most sizes of size at any time are performing their respective tasks. When all threads in the thread pool are running, subsequent new threads will wait in the unbounded queue until there are idle threads. If the thread thread terminates the exit during the execution of a task, a new one will replace the previous thread to continue the execution of the subsequent task. Threads in the thread pool persist until a thread is shown to close.
Executerservice Fixedpool = executors. Newfixedthreadpool (5); Create a thread pool that has 5 threads fixed
Create a thread pool that can create threads as needed, when a task comes up, if there are free threads in the thread pool, first with the idle thread, and no new thread is created. This thread pool typically improves performance for performing short-lived asynchronous tasks (short-term asynchronous task). The default free 60s thread is removed from the thread pool and will not occupy any resources if it is idle for a long time. However, in my personal experience, this kind of thread pool should be used with caution, which often causes out-of-heap memory overflow, which results in slow application response and finally leads to downtime.
Executerservice Fixedpool = executors. Newcachedthreadpool ();
- Newsinglethreadexecutor ()
Create a Executor that uses a single worker thread to run the thread in a unbounded queue. Each task is guaranteed to be executed sequentially. Some people say this is not newfixedthreadpool (1), wrong. Look at the source know the outside also covered a layer of finalizabledelegatedexecutorservice, this is a static inner class of executors, this inner class inherits Delegatedexecutorservice, The Executorservice implementation that is returned contains only some of the methods defined by the Executorservice interface, unlike Newfixedthreadpool, which has its own extension. The difference between source comments is that newsinglethreadexecutor can guarantee that when other threads are used, the returned executor is not reconfigured.
Executerservice Fixedpool = executors. Newsinglethreadexecutor ();
- newscheduledthreadpool (int size)
Creates a thread pool that can schedule a command to run after a given delay or perform it on a regular basis. This is a thread pool of unbounded size. The main method of implementation is Scheduleatfixedrate and Schedulewithfixeddelay method, the final core method is Delayedexecute, what is the difference between these two methods, simply speaking, Scheduleatfixedrate is based on the start of the task execution time for the delay time, Schedulewithfixeddelay is the task execution end time for the delay time starting point.
Next, the use of some of the classes used in the contract with the analysis
1) Signal Volume Semaphore:
A count semaphore that maintains a set of licenses. In layman's terms, it is the use of limited shared resource records.
Take an example of everyday life: There are 20 people to register the information form, but only 3 pens, a person used to use after a person, until everyone used up.
How did we design the contract before it was contracted?
Define a variable A, with synchronized decoration, a value of 3, a new 20 threads to simulate 20 people access, each person with a pen before the first to see if there is a spare pen, if there is, use, and the variable A to reduce 1, using the completion, then put back, the variable a plus 1, Access to variable A is mutually exclusive for each thread. Synchronized is a heavy-weight synchronous operation that involves switching between a user state and a nuclear mindset, so the performance is general.
Let's take a look at how the semaphore is implemented, and the idea of semaphore implementation is similar to the above. It's just that semaphore has helped us synchronize, there are two key methods:
- acquire () Get a semaphore license
- release () release a semaphore license
There are several other methods: Availablepermits () returns the number of licenses available for the semaphore, talk is cheap show me the code:
Public class Semaphoretest extends thread{
Private String name;
Private Semaphore sh;
Public Semaphoretest (String name,semaphore sh) {
this. Name = name;
this. sh = sh;
}
Public void Run () {
if (Sh.availablepermits () >0) {
System. out. println ("with pen");
}Else{
System. out. println ("The pen is gone, etc.");
}
Try {
Sh.acquire();//signal volume minus 1
System. out. println (this. name+ "in Pen");
Thread. Sleep ((long) (Math. Random() *1000));
Sh.release ();
System. out. println (the "this. name+" is used up);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
Public Static void Main (string[] args) {
Executorservice es = executors. Newcachedthreadpool ();
Semaphore sh = new Semaphore (3);
for (int i=0;i<20;i++) {
Es.submit (new semaphoretest (i+ "", SH));
}
Es.shutdown ();
}
}
The above code can be run directly.
This semaphore is how to synchronize resources, you need to read the JDK related source code. The core class is Abstractqueuedsynchronizer, which implements a FIFO list in which node represents the list node, which has attributes such as prev, Next, Thread, and so on before the node and thread. And each need to implement a personalized synchronization mechanism in the contract to extend the class to achieve different synchronization capabilities. such as semaphore, Countdownlatch, Cyclicbarrier, and so on, the specific principle to analyze the source code, length longer, here do not expand, interested can study, the volatile keyword, CAS and so will have a deeper understanding.
2) Countdownlatch
Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately.
2 more important methods: Countdown () and await ()
Here is a common example: the tour guide brought 20 people to the restaurant to eat, to wait until 20 people to the QI, only to start eating, but also to wait until 20 people have finished eating, can continue the next attraction.
To see how you would do without concurrent packages, first set 20 people to come and eat the signs, each thread came over to change their logo, the main program for or while the loop monitoring, stop all arrival and eat to continue. If it is 100 people and 1000 people, it is rather bloated.
Implementation of Countdownlatch:
Public class countdownlautchtest {
Public Static void Main (string[] args) {
Executorservice es = executors. Newfixedthreadpool (20);
Final Countdownlatch Endflag = new countdownlatch (20);
Final Countdownlatch Startflag = new countdownlatch (1);
Final Countdownlatch Comeflag = new countdownlatch (20);
for (int i=0;i<20;i++) {
Final int J = i + 1;
Runnable person = new Runnable () {
@Override
Public void Run () {
System. out. println (j+ "visitor");
Comeflag.countdown ();
Try {
Startflag.await ();
Thread. Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
System. out. println (j+ "is finished");
Endflag.countdown ();
}
}
};
Es.submit (person);
}
Try {
Comeflag.await (); Make sure everyone's here.
System. out. println ("People are all together, everybody Eats");
Startflag.countdown ();//Open Eat
Endflag.await ();//Waiting for everyone to finish eating.
System. out. println ("All finished, continue to the next attraction");
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Es.shutdown ();
}
}
Countdownlatch is an irreversible descending count operation, so the above code defines 2 symbols for waiting and eating respectively. If you need to repeat the count, you need to use the following class: Cyclicbarrier.
3) Cyclicbarrier
A synchronization helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.
Or the above example, add a bit of scene, eat dinner also want to play, play end return home. Let's take a look at how Cyclicbarrier is implemented, on the code:
Public class cyclicbarriertest {
Public Static void Main (string[] args) {
Final Cyclicbarrier barrier = new cyclicbarrier (20);
Final Executorservice es = executors. Newfixedthreadpool (20);
System. out. println ("* * * * * * * * * * * *)";
for (int i=0;i<20;i++) {
Final int j = i+1;
Runnable person = new Runnable () {
@Override
Public void Run () {
Try {
System. out. println (j+ "No.");
if (Barrier.await () ==0) {
System. out. println ("* * * * * * * * * * * * * * * * * *);
}
System. out. println (j+ "open to eat");
if (Barrier.await () ==0) {
System. out. println ("* * * * * * * * * * * * * * *);
}
System. out. println (j+ "The game is ready");
if (Barrier.await () ==0) {
System. out. println ("* * * * * * * * * * * * *]);
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
};
Es.submit (person);
}
Es.shutdown ();
}
}
Code to run directly, you should compare understood bar, here is a little trick, the code in the If (barrier.await () ==0) This condition, a bit similar to the countdownlatch await down execution conditions, each judgment will be reduced by 1, to 0, That is, the wait for all threads is completed and the following operation continues.
Conclusion
About and contract some commonly used classes to introduce here, the work of how to use specific analysis of the various business scenarios, choose the appropriate method, adapt, comprehend by analogy bar, follow-up will introduce the lock source code and implementation, involving the principle of AQS.
Not finished, to be continued ...
Java Concurrency Artifact Concurrent Package (i)