There is only one purpose of multithreading, which is to make better use of CPU resources, because all multithreaded code can be implemented by single thread. Say this is only half right, because the reaction "multi-Role" of the program code, at least each role to give him a thread bar, or even the actual scene can not be simulated, of course, it is not possible to use a single thread to achieve: for example, 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, in order to avoid misunderstanding. Multithreading: Refers to the program (a process) when the runtime produces more than one thread parallel and concurrency: Parallel: Multiple CPU instances or multiple machines simultaneously execute a piece of processing logic, is true at the same time. Concurrency: Through the CPU scheduling algorithm, let the user appear to execute simultaneously, actually from the CPU operation level is not real at the same time. Concurrency often has a common resource in the scene, so for this common resource is often a bottleneck, we will use TPS or QPS to reflect the processing power of the system. Concurrency and parallel thread safety: often used to depict a piece of code. In the case of concurrency, the code is multithreaded and the scheduling order of the threads does not affect any results. This time using multi-threading, we only 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 non-transactional transfer codes: void TransferMoney (user from, user to, float amount) {To.setmoney ( To.getbalance () + amount); From.setmoney (from.getbalance ()-amount);} Synchronization: Synchronization in Java refers to the use of human control and scheduling, to ensure that multi-threaded access to shared resources become thread-safe, to ensure the accuracy of the results. Simply add the @synchronized keyword as the above code. In ensuring that the results are accurate at the same time, improve performance, is a good program. Thread safety has a higher priority than performance. All right, let's get started. I'm going to break into several points to summarize the content that involves multithreading: tie good Horse: thread state internal strength Heart: Each object has a method (mechanism) Tai-Quan: Basic threading Class nine Yin Canon: Advanced multithreading control class tie good horse: The state of the thread first two graphs: thread state thread state transitions a variety of states at a glance, It is worth mentioning that the "blocked" state: the thread may encounter blocking (blocked) in the process of running call the join () and sleep () method, sleep () time ended or interrupted, join () interrupted, IO completion will return to the runnable state, waiting for the JVM to dispatch. Call Wait () so that the thread is in the waiting pool (waitBlocked Pool) until notify ()/notifyall (), the thread is woken up to the lock pool (lock blocked Pool), releasing the sync lock to bring the thread back to the operational state (Runnable) to the running state of the line loads Sync lock ( Synchronized) to enter (the lock blocked pool), the sync Lock is released into the operational state (Runnable). In addition, the thread in the runnable state is in the thread being dispatched, at which point the scheduling order is not necessarily. The yield method in the thread class allows a thread of the running state to be transferred to Runnable. Internal organs Heart: Each object has a method (mechanism) synchronized, wait, notify is any object has a synchronization tool. Let's get to know them first. Monitor they are the manual thread scheduling tool that is applied to the synchronization problem. Speaking of its essence, the concept of monitor must be clarified first, and every object in Java has a monitor to monitor the re-entry of concurrent code. The monitor does not work when it is not multithreaded, and the monitor works if it is within 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 wait, other threads can go into the synchronization block execution. When a code does not hold the monitor's right to use (in 5 of the State, i.e. out of sync block) to wait or notify, it throws java.lang.IllegalMonitorStateException. It is also included in the synchronized block to invoke the wait/notify of another object, because different objects have different monitors, and this exception is thrown. Usage: Synchronized: code block: as follows, in a multithreaded environment, the method in the synchronized block acquires the monitor of the lock instance, and if the instance is the same, only one thread can execute the block content public class Thread1 implements Runnable {Object lock; public void Run () {synchronized (lock) {: Do something}}} is used directly in the method: the effect of locking with lock in the above code, actually getting the monitor of the Thread1 class. Further, if the static method is decorated, all instances of the class are locked. public class Thread1 ImplemEnts Runnable {public synchronized void run () {: Do something}}synchronized, wait, notify combination: Typical scenario producer consumer issues/** * producers produce products to the clerk */public synchronized void produce () {if (th Is.product >= max_product) {try {wait (); SYSTEM.OUT.PRINTLN ("Product is full, please wait for reproduction"); } catch (Interruptedexception e) {e.printstacktrace ();} return; } this.product++; System.out.println ("producer Production" + This.product + "products."); Notifyall (); Notifies the waiting area that the consumer can take out the product}/** * The consumer takes the product from the clerk */public synchronized void consume () {if (this.product <= min_product) {try {WA It (); System.out.println ("Out of stock, take later"); } catch (Interruptedexception e) {e.printstacktrace ();} return; } System.out.println ("The consumer took the first" + This.product + "products."); this.product--; Notifyall (); Inform the producer of the wait to be able to produce a}volatile multi-threading memory model: Main memories, working (line stacks), when processing the data, the thread will load the value from main memory to the local stack, complete operation and then save back ( The role of volatile keywords: every action against the variable fires a load and save. Volatile variables used for multithreading, if not volatile or final decorated, are likely to produce unpredictable results (another thread modifies the value, but then a thread sees the value before it is modified). In fact, the same property itself has only one copy of the same instance. But multithreading is a cache of values, in essence, volAtile is not going to cache, directly take value. Adding volatile in the case of thread security can compromise performance. Chang Quan: Basic Thread Class Basic threading class refers to the thread class, runnable interface, callable interface thread class implements the Runnable interface, the method of starting a thread: MyThread my = new MyThread (); My.start (); Thread class Related methods://When the thread can transfer CPU control, let other ready state threads run (toggle) public static Thread.yield ()//pause for a while public static thread.sleep ()// Calling Other.join () in one thread waits for the other to finish before continuing with this thread. Public join ()//The last two functions can be interrupted public interrupte () interrupts about interrupts: it does not break a running thread as the Stop method does. The thread periodically detects the interrupt identity bit to determine if the thread should be interrupted (the interrupt identity value is true). The terminal only affects the wait state, sleep state, and join status. The interrupted thread throws interruptedexception. Thread.interrupted () checks if the current thread is interrupted, and the return booleansynchronized cannot be interrupted during the lock. Interrupts are a state! The interrupt () method simply resets the state to true. So the normal running program does not detect the state, it will not terminate, and wait and other blocking methods will check and throw an exception. If you add while (!) in the normal running program. Thread.interrupted ()), you can also leave the code body thread class best practice after an outage: it is best to set the thread name Thread.Name when writing, and set the thread group Threadgroup for easy administration. In the event of a problem, the print line stacks (jstack-pid) can see at a glance which thread is out of the question, what the thread is doing. How to get exceptions in threads cannot use Try,catch to get exceptions in threads runnable similar to thread callablefuture mode: One of the concurrency patterns can have two forms, namely, no blocking and blocking, respectively Isdone and get. Where the future object is used to hold the return value of the thread and the state executorservice e = Executors.newfixedthreadpool (3); /The/submit method has multiple parameter versions and supports callable to support the Runnable interface type. Future future = E.submit (New mycallable ()), Future.isdone ()//return true,false nonblocking future.get ()//return value, Block until the thread runs the end nine Yin Canon: Advanced multi-threaded control class above are the internal strength of the heart, the next is the actual project used in the tool, Java1.5 provides a very efficient and practical multithreaded package: Java.util.concurrent, provides a lot of advanced tools, can help developers write efficient, maintainable, and well-structured Java multi-threaded program. 1.ThreadLocal class use: Saves independent variables of the thread. For a thread class (inherited from thread) when you use threadlocal to maintain variables, Threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy without affecting the copy of the other thread. Commonly used in user Login control, such as recording session information. Implementation: Each thread holds a variable of type Treadlocalmap (the class is a lightweight map, the same as map, the difference is that the bucket is placed in the entry rather than the entry list. function is also a map. ) takes itself as key and targets as value. The primary method is get () and set (T a), and a is returned when the set is maintained in map with a threadlocal-a,get. The threadlocal is a special container. 2. Atomic Class (Atomicinteger, Atomicboolean ... If you use Atomic wrapper class (Atomic wrapper class) such as Atomicinteger (Atomic integer), or use your own to guarantee the operation of the atom, it is equivalent to synchronized// The return value is booleanatomicinteger.compareandset (int expect,int Update) This method can be used to implement optimistic locking, consider the following scenario that was originally mentioned in the article: A to B payment of 10 yuan, a deducted 10 yuan, B to add 10 yuan. At this point C gives B2, but B's add 10 code is about: if (B.value.compareandset (old, value)) {return;} else{//try again//If that fails, rollback and log}atomicReference (atomic Reference) for Atomicreference, maybe the object will appear, the property is missing, that is oldobject = = Current, but Oldobject.getpropertya! = Current.getpropertya. At this time, the atomicstampedreference comes in handy. This is also a very common idea, that is, plus version number 3. Lock class Lock: Inside the Java.util.concurrent package. A total of three implementations: ReentrantLockReentrantReadWriteLock.ReadLockReentrantReadWriteLock.WriteLock The main purpose is like synchronized, Both are designed to solve the synchronization problem and deal with the resource disputes arising from the technology. Functionally similar but with some differences. The difference is as follows: Lock is more flexible, you can freely define the locking order of multiple locks (synchronized to the first addition of the post-solution sequence) to provide a variety of locking schemes, lock blocking, trylock non-blocking, lockinterruptily can be interrupted, There is also a trylock version with a time-out. In essence and monitor lock (that is, synchronized is the same) the greater the capacity, the greater the responsibility, must control the lock and unlock, otherwise it will lead to disaster. And the combination of the condition class. Higher performance, for example: synchronized and lock performance comparison reentrantlock The meaning of reentrant is that the thread holding the lock can continue to hold it, and the number of times it is released will not really release the lock. Use the method: 1. First new instance static Reentrantlock r=new Reentrantlock (); 2. Lock R.lock () or R.lo ckinterruptibly (); There is a difference here, and the latter can be interrupted. When a thread is lock, the B thread is blocked, and if it is lockinterruptibly, then after calling B.interrupt (), the B thread exits the block and discards the scramble for the resource into the catch block. (If you use the latter, you must throw interruptable exception or catch) 3. Release the lock R.unlock () must do! What must be done, put in finally. To prevent anomalies from jumping out of normal processes, leading to disaster. Here's a little bit of knowledge that finally can be trusted: tested, even if it happened outofmemoryerror,finallThe execution of statements in the Y block can also be guaranteed. Reentrantreadwritelock can be re-entered read-write lock (an 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 and read are not mutually exclusive. An efficient thread-safe code that can implement concurrent reads 4. Container class Here is a discussion of the more commonly used two: Blockingqueueconcurrenthashmapblockingqueue blocking queue. This class is an important class under the Java.util.concurrent package, and through the learning of 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 pipeline, especially suitable for some scenarios of FIFO strategy. The common queue interface is mainly implemented with Priorityqueue (priority queue), and is interested in the ability to study blockingqueue added multi-threaded collaboration on the basis of queues: Blockingqueue In addition to the traditional queue function (two columns to the left of the table) Also provides blocking interfaces for put and take, blocking interface offer and poll with timeout features. A put blocks when the queue is full, wakes up when there is space, and takes a block when the queue is empty until something is picked up. Used in the producer-consumer model is especially useful and is an artifact. The common blocking queues are: arraylistblockingqueuelinkedlistblockingqueuedelayqueuesynchronousqueueconcurrenthashmap efficient thread-safe hash map. Compare Hashtable, Concurrenthashmap, HASHMAP5. The concept of management class management classes is more generic, and is used to manage threads that are not multithreaded in themselves, but provide some mechanism to use the tools described above to do some encapsulation. Learn about the management classes that are worth mentioning: system-level management classes under the Threadpoolexecutor and JMX frameworks Threadmxbeanthreadpoolexecutor If you don't understand this class, you should know 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 a variable size thread pool, which allocates threads according to the number of tasks,//The second is a single thread pool, which is equivalent to Fixedthreadpool (1)//The third is a fixed size thread pooling. Then run E.execute (New Myrunnableimpl ()); This class is implemented through Threadpoolexecutor, and mastering it helps to understand the management of the thread pool, in essence, They are all the implementation versions of the Threadpoolexecutor class. See Javadoc:threadpoolexecutor parameter Interpretation translation: corepoolsize: Pool inline initial and minimum, even if it is idle, the number of threads is maintained. Maximumpoolsize: Thread maximum, thread growth will never exceed this value. KeepAliveTime: When the pool thread is higher than corepoolsize, the amount of time that is spent in excess of idle threads is recycled. Before recycling is in the Wait state unit: Time unit, you can use an instance of Timeunit, such as Timeunit.milliseconds WorkQueue: Waiting place for a task to be entered (Runnable), which mainly affects the scheduling strategy, such as fairness or not, Whether it produces starvation (starving) Threadfactory: The Thread factory class, which has a default implementation, needs to implement the Threadfactory interface and pass in as a parameter if there is a custom need.
Java Multithreaded Learning