Author: Know Rice, Mowgli (author of Jane book)
Turn from: Http://www.jianshu.com/p/40d4c7aebd66
Multithreading has only one purpose, that is, better use of CPU resources, because all multithreaded code can be implemented in a single thread. Say this is only half right, because the response to "multiple roles" of the program code, at least each character to give him a thread, or even the actual scene can not be simulated, of course, cannot be said to be able to use a single thread to achieve: such as the most common "producer, consumer model."
Many people are not clear about some of these concepts, such as synchronization, concurrency and so on, let us first set up a data dictionary, so as not to create misunderstandings. Multithreading: Refers to the program (a process) runtime generated more than one thread parallel and concurrency: Parallel: Multiple CPU instances or multiple machines simultaneously executing a section of processing logic, is true at the same time. Concurrency: Through the CPU scheduling algorithm, so that users look at the same time, actually from the CPU operating level is not true at the same time. Concurrency often has common resources in the scene, then for this common resources often create bottlenecks, we will use TPS or QPS to reflect the processing capacity of the system.
Concurrency and parallel thread safety: often used to depict a piece of code. In the case of concurrency, the code is used in multithreading, and the scheduling order of the thread does not affect any results. This time using multithreading, we just need to focus on the system's memory, the CPU is not enough. Conversely, thread insecurity means that the scheduling order of threads affects the end result, such as transfer code without transactions:
void TransferMoney (user from, user to, float amount) {
To.setmoney (to.getbalance () + amount);
From.setmoney (from.getbalance ()-amount);
Synchronization: Java synchronization refers to the use of artificial control and scheduling, to ensure that the shared resources of multi-threaded access to become thread-safe, to ensure the accuracy of the results. As the above code simply adds the @synchronized keyword. It is a good program to improve performance while guaranteeing the accuracy of the results. Thread-safe precedence is higher than performance.
All right, let's get started. I'm going to split up into a few points to summarize the content involved in multithreading: a good stance: the thread of the state of internal strength: Each object has a method (mechanism) Tai Quan: Basic thread Class nine Yin Canon: Advanced multithreaded Control class stance: The state of the thread
Two pictures First:
Thread state
Thread state transitions
Various states at a glance, it is worth mentioning the "blocked" this state:
The thread may encounter a blocking (Blocked) condition in the course of the running call join () and sleep () method, the time is over or interrupted, join () interrupt, IO completion will return to the runnable state, waiting for the JVM scheduling. Call Wait (), so that the thread is in the waiting pool (the waits blocked pool) until notify ()/notifyall (), the thread is awakened to be placed in the lock pool (lock blocked pool), Releasing the sync lock causes the thread to return to the operational state (Runnable) the line Chengga Synchronous Lock (Synchronized) of the running state to enter (lock blocked pool), and the synchronous lock is released into the operational state (Runnable).
In addition, the thread in the runnable state is in the scheduled thread, at which point the dispatch order is not necessarily. The yield method in the thread class allows a running state thread to be transferred to Runnable. Internal strength : Every object has a method (mechanism)
Synchronized, wait, notify is a synchronization tool that any object has. Let's get to know them first.
Monitor
They are manual thread scheduling tools that apply to synchronization issues. In essence, the concept of monitor should be defined first, and each object in Java has a monitor to monitor the reentry of concurrent code. The monitor does not work when it is not multithreaded, whereas the monitor works in the synchronized range.
The wait/notify must exist in the synchronized block. Also, these three keywords are for the same monitor (the monitor for an object). This means that after the wait, other threads can enter the synchronization block for execution.
When a code does not hold the right to use the monitor (as in the figure of 5, that is, out of sync block) to wait or notify, will throw java.lang.IllegalMonitorStateException. It is also included in the synchronized block to invoke the wait/notify of another object, because the monitor for the different objects is different and the exception is thrown.
Again usage: Synchronized alone: code block: as follows, in a multithreaded environment, the method in the synchronized block gets the monitor for the lock instance, and if the instance is the same, then only one thread can execute the block content
public class Thread1 implements Runnable {
Object lock;
public void Run () {
synchronized (lock) {
... Do something}}}
Directly used in the method: the equivalent of locking in the above code to lock the effect of the actual acquisition of the Thread1 class of Monitor. Further, all instances of the class are locked if the static method is decorated.
public class Thread1 implements Runnable {public
synchronized void Run () {
. Do something
}
}
Synchronized, wait, notify combination: A typical scenario producer consumer problem
/** * producer produced products to the clerk * * Public synchronized void produce () {if (this.product >= MA
X_product) {try {wait ();
SYSTEM.OUT.PRINTLN ("The product is full, please wait for reproduction");
catch (Interruptedexception e) {e.printstacktrace ();
} return;
} this.product++;
System.out.println ("producer produces the first" + This.product + "a product."); Notifyall (); Notify the consumer of the waiting area to take out the product}/** * Consumers from the clerk to the product/public synchronized void consume () {if (this.product <= MI
N_product) {try {wait ();
System.out.println ("Out of stock, later to take");
catch (Interruptedexception e) {e.printstacktrace ();
} return;
SYSTEM.OUT.PRINTLN ("Consumers take the first" + This.product + "product.");
this.product--; Notifyall (); Notice that the producer waiting to go can produce the product.}
volatile
Multithreaded memory model: main memory (main memory), working memory (line stacks), when processing data, the thread will be the value from main memory load to the local stack, complete the operation and then save back ( Volatile keyword: Each action on the variable fires once the load and save.
Volatile
Variables used for multithreading are likely to produce unpredictable results if they are not volatile or final modified (another thread modifies this value, but later on a thread sees the value before the modification). In fact, the same property itself has only one copy of the same instance. But multithreading is the cache value, in essence, volatile is not to cache, direct value. Adding volatile in the case of thread safety will sacrifice performance. Tai Quan: Basic Thread Class
The basic thread class refers to the thread class, the Runnable interface, the callable interface
The thread class implements the Runnable interface, and starts a thread method:
Mythread my = new Mythread ();
My.start ();
thread class related methods:
The current thread can transfer CPU control, let the other Ready state thread run (toggle) public
static Thread.yield ()//pause for a period of
time public
static Thread.Sleep ()
//Call Other.join () in one thread and wait for the other to execute before proceeding with this thread. Public
Join ()
//The latter two functions can be interrupted by public
Interrupte ()
about interrupts : it does not interrupt a running thread as the Stop method does. The thread periodically detects the interrupt identity bit to determine whether the thread should be interrupted (whether the interrupt identity value is true). The terminal affects only the wait state, the sleep state, and the join state. The interrupted thread throws a interruptedexception.
Thread.interrupted () checks whether the current thread has broken, returns a Boolean
Synchronized cannot be interrupted in the process of being locked.
Interrupts are a state. The interrupt () method simply resets this state to true. So the normal operation of the program does not detect the state, it will not terminate, and wait, such as blocking methods to check and throw an exception. If you add a while (!) in a normally running program. Thread.interrupted ()), you can also leave the code body after the interrupt
Thread class Best Practices :
It is best to set the thread name Thread.Name and set the thread group Threadgroup to facilitate management. In the presence of a problem, the print line stacks (jstack-pid) at a glance can see which thread is the problem, what this thread is doing.
How to get exceptions in a thread
You cannot use Try,catch to get exceptions in a thread Runnable
Similar to the thread callable
Future mode: One of the concurrency patterns that can have two forms, namely, no blocking and blocking, respectively, Isdone and get. Where the future object holds the return value of the thread and the state
Executorservice e = Executors.newfixedthreadpool (3);
The Submit method has multiple parameter versions, and support callable can also support Runnable interface types.
Future Future = e.submit (New mycallable ());
Future.isdone ()//return true,false No blocking
future.get ()//return value, blocking until the thread runs the end
Nine Yin Canon: Advanced multithreaded Control class
Above all belong to the internal strength, next is the actual project commonly used tools, Java1.5 provides a very efficient and practical multithreaded package: Java.util.concurrent, provides a number of advanced tools to help developers write efficient, easy to maintain, A clear, structured Java multithreaded programming. 1.ThreadLocal class
Use: Save the thread's independent variables. For a thread class (inherited from Thread)
When using threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently alter its own copy without affecting the counterpart of the other thread. Often used for user login control, such as recording session information.
Implementation: Each thread holds a variable of type Treadlocalmap (the class is a lightweight map that functions as a map, with the difference being that a entry is placed in a bucket rather than a entry list. function is still a map. ) is the key in itself and the target is value.
The Main method is get () and set (T a), which returns a when a threadlocal-> A,get is maintained in the map after set. The threadlocal is a special container. 2. Atomic Class (Atomicinteger, Atomicboolean ...). )
If you use atomic wrapper class such as Atomicinteger, or you use your own to guarantee the operation of the atom, it is equivalent to synchronized
The return value is Boolean
atomicinteger.compareandset (int expect,int update)
This method can be used to realize optimistic lock, consider the following scene originally mentioned in the article: A to pay B 10 yuan, a buckle 10 yuan, B to add 10 yuan. At this time C give B2 yuan, but B's plus 10 code is about:
if (B.value.compareandset (old, value)) {return
;
} else{
//try again
//If that fails, rollback and log
}
Atomicreference
For Atomicreference, perhaps the object will appear, the property is lost, that is, oldobject = = Current, but Oldobject.getpropertya!= Current.getpropertya.
At this time, Atomicstampedreference came in handy. This is also a very common idea, that is, add version number 3.Lock class
Lock: Inside the Java.util.concurrent package. Total three implementations: Reentrantlock Reentrantreadwritelock.readlock Reentrantreadwritelock.writelock
The main purpose is the same as synchronized, both of which are designed to solve the problem of synchronization and to deal with resource disputes. Features are similar but there are some differences.
The difference is as follows: Lock more flexible, you can freely define the shackles of multiple locks to unlock the order (synchronized to the first added after the order of the solution) to provide a variety of locking schemes, lock blocking, trylock-free, lockinterruptily can be interrupted, There is also a trylock version with the timeout period. In essence, the greater the ability to monitor the lock (i.e. synchronized is the same), the greater the responsibility, the better to control lock and unlock, otherwise it can cause disaster. And the combination of condition classes. Performance is higher, compared to the following figure:
Synchronized and lock performance comparisons
Reentrantlock
The meaning of reentrant is that the thread holding the lock can continue to hold, and the number of equals is freed before the lock is actually released.
The use method is:
1. A new instance first
Static Reentrantlock r=new reentrantlock ();
2. Add lock
R.lock () or r.lockinterruptibly ();
There is a difference here, and the latter can be interrupted. After a thread lock, b threads block, if it is lockinterruptibly, then after the call to B.interrupt (), b thread exits blocking and discards the scramble for resources to enter the catch block. (If you use the latter, you must throw interruptable exception or catch)
3. Release lock
R.unlock ()
Must do. What must be done, should be put in finally. To prevent exceptions from escaping the normal process, resulting in disaster. Here is a little bit of knowledge to add, finally can be trusted: After testing, even if the outofmemoryerror,finally block in the execution of the statement can be guaranteed.
Reentrantreadwritelock
Can be read-write lock (one implementation of read-write lock)
Reentrantreadwritelock lock = new Reentrantreadwritelock ()
readlock r = Lock.readlock ();
Writelock w = lock.writelock ();
Both have lock,unlock methods. Write, write and read mutually exclusive, read not mutually exclusive. Efficient thread-safe code that enables concurrent reads 4. Container class
Here is a discussion of the more commonly used two: Blockingqueue Concurrenthashmap
Blockingqueue
Blocks queues. This class is an important class under the Java.util.concurrent package, and by learning about the queue, this queue is a one-way queue that can add elements to the queue header and delete or remove elements at the end of the team. Similar to a pipe, especially for some scenarios where the first-out strategy is used. The common queue interface is mainly implemented with Priorityqueue (priority queue), which is interested to study
Blockingqueue adds the capabilities of multithreaded collaboration on a queue basis:
Blockingqueue
In addition to the traditional queue function (two columns to the left of the table), the blocking interface put and take, the blocking interface with the timeout function, and the poll are provided. Put will block when the queue is full, until there is room to wake up, and take to block when the queue is empty until something is taken. The producer-consumer model is particularly useful and is an artifact.
Common blocking queues are: Arraylistblockingqueue linkedlistblockingqueue delayqueue Synchronousqueue
Concurrenthashmap
Efficient thread-safe hash map. Please compare Hashtable, Concurrenthashmap, HashMap 5. Management class
The concept of management classes is rather generic and is used to manage threads, which are not multi-threaded in themselves, but provide some mechanism to do some encapsulation using the tools described above.
Learn about the management classes that are worth mentioning: system-level management classes under the Threadpoolexecutor and JMX framework Threadmxbean
Threadpoolexecutor
If you do not understand this class, you should understand the Executorservice mentioned earlier, it is very convenient to open a thread pool of your own:
Executorservice e = Executors.newcachedthreadpool ();
Executorservice e = Executors.newsinglethreadexecutor ();
Executorservice e = Executors.newfixedthreadpool (3);
The first is the variable size thread pool, which assigns threads according to the number of tasks,
//The second is a single thread pool, equivalent to Fixedthreadpool (1)
//The third is a fixed size thread pool.
//Then run
e.execute (New Myrunnableimpl ());
This class is implemented internally through Threadpoolexecutor, and mastering this class helps to understand the management of thread pools, which are essentially various implementations of the Threadpoolexecutor class. See Javadoc:
Threadpoolexecutor parameter explanation
translates:
corepoolsize : Pool inner-thread initial and minimum values, even if idle, keep the number of threads.
maximumpoolsize : Thread maximum, thread growth will never exceed this value.
KeepAliveTime : When the number of threads in the pool is higher than corepoolsize, the amount of idle thread that is wasted is recycled. Before the recycle in wait state
Unit :
time units, you can use an instance of Timeunit, such as Timeunit.milliseconds
workqueue : The waiting place for the pending task (Runnable), which primarily affects the scheduling policy, such as whether it is fair or not (starving)
threadfactory : Thread factory class, with default implementation , if you have custom needs, you need to implement the Threadfactory interface yourself and pass it as a parameter to the
text/meter, Mowgli (Jane book author)
Original link: Http://www.jianshu.com/p/40d4c7aebd66
Copyright belongs to the author, reproduced please contact the author to obtain authorization, and labeled "Jane book author."