Multithreading in Java you just have to read this one.

Source: Internet
Author: User
Tags finally block volatile

from: Jane book

Know Rice, Mowgli

Links: Http://www.jianshu.com/p/40d4c7aebd66

cited

If you still have doubts about what a thread is, what is a process, please Google first, because these two concepts are not within the scope of this article.

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 executing a processing logic at the same time are 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 parallelism

    • 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. In turn, thread insecurity means that the scheduling order of threads affects the end result, such as no transaction transfer code:

void float amount) {  + amount);   - amount);}

    • Sync: 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 split into several points to summarize what's involved in Multithreading:

1, Tie good horse: The state of the thread

2, internal organs heart: Each object has a method (mechanism)

3, the founder of Chang Quan: Basic Threading Class

4, nine Yin Canon: advanced Multi-threaded control class

Tie the horse: The state of the thread

Let's take two pictures first:



Thread state

Thread state transitions

Various states at a glance, it is worth mentioning that the "blocked" this state:

A thread may experience a blocking (Blocked) condition during running

1, call the join () and sleep () method, sleep () time ends or be interrupted, join () interrupt, IO completion will return to the runnable state, waiting for the JVM to dispatch.

2. Call Wait () so that the thread is in the waiting pool (wait blocked pool) until notify ()/notifyall (), the thread is awakened and placed in the lock pool (lock blocked). Releasing a sync lock to bring the thread back to the operational state (Runnable)

3, the running state of the line loads synchronous lock (Synchronized) to enter (lock blocked pool), the synchronization 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: The method of each object (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 are applied to synchronization problems. 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.

To speak again of usage:

    • Synchronized used alone:

    • Code block: As below, 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 Implements Runnable {   Object lock;     Public void run () {         synchronized(lock) {         :  Do something       }    }}

    • Directly used in the method: equivalent to the above code with lock locking effect, actually obtained is the Thread1 class of Monitor. Further, if the static method is decorated, all instances of the class are locked.

 Public class Implements Runnable {   Object lock;     Public void run () {         synchronized(lock) {         :  Do something       }    }}

    • Synchronized, wait, notify combination: Typical scenario producer consumer issues

/*** The product produced by the producer is given to the clerk*/   Public synchronized voidProduce () {if( This. Product >=max_product) {          Try{wait (); System.out.println ("Product is full, please wait to reproduce"); }          Catch(interruptedexception e) {e.printstacktrace (); }          return; }       This. product++; System.out.println ("Producer Production section" + This. Product + "products.");   Notifyall (); //notifies the waiting area that the consumer can remove the product}/*** Consumers take products from shop assistants*/   Public synchronized voidconsume () {if( This. Product <=min_product) {          Try{wait (); System.out.println ("Out of stock, take it later"); }           Catch(interruptedexception e) {e.printstacktrace (); }          return; } System.out.println ("The consumer took out the first" + This. Product + "products.");  This. product--;   Notifyall (); //inform the producers who are waiting to produce the products.}

volatile

multi-Threading memory Model: Main memories, working memory (line stacks), when processing data, the thread will load the value from 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. However, multithreading is the cache value, in essence, volatile is not to cache, directly take value. Adding volatile in the case of thread security can compromise performance.

Chang Quan: Basic Threading Class

The basic threading class refers to the thread class, the Runnable interface, the callable interface


The thread class implements the Runnable interface, starting a thread's method:

New  MyThread (); My.start ();

Thread Class related methods:

// the current thread can transfer CPU control and allow other ready state threads to run (toggle)  Public Static  // pause for some time publicstatic  thread.sleep ()// calling Other.join () in one thread waits for the other to finish before continuing with this thread.   Public Join ()//After both functions can be interrupted public interrupte ()

about interrupts : it does not break a running thread like 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 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 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 after the interrupt

Thread Class Best Practices:


When writing, it is best to set the thread name Thread.Name and set the thread group Threadgroup to facilitate management. 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 a thread


You cannot use Try,catch to get exceptions in a thread

Runnable

Similar to Thread

callable

Future mode: One of the concurrency patterns, which can take two forms, namely, no blocking and blocking, respectively Isdone and get. Where the future object is used to store the return value and state of the thread

Executorservice e = executors.newfixedthreadpool (3//The Submit method has multiple parameter versions, and support callable can also support the Runnable interface type. Future future = E.submit (new/ /// return value, blocking until the thread finishes running

Nine Yin Canon: Advanced Multithreading Control class

The above is 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 number of advanced tools to help developers write efficient, easy to maintain, A well-structured Java multithreaded thread.

1, Threadlocal class

Useful: Saves the thread's independent variables. 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 such as Atomicinteger, or use your own to guarantee the operation of the atom, it is equivalent to synchronized

// return value is Boolean Atomicinteger.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

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, add version number

3. Lock Class

Lock: Inside the Java.util.concurrent package. A total of three implementations:

    • Reentrantlock

    • Reentrantreadwritelock.readlock

    • Reentrantreadwritelock.writelock

The main purpose is the same as synchronized, both are to solve the synchronization problem, dealing with resource disputes arising from the technology. Functionally similar but with some differences.

The difference is as follows :

1, lock more flexible, you can freely define the chain of the lock to unlock the order (synchronized to follow the order of the first addition)

2, provide a variety of locking scheme, lock blocking type, trylock non-blocking, lockinterruptily can be interrupted, there are trylock with the time-out version.

3, essentially and monitor lock (that is, synchronized is the same)

4, the greater the capacity, the greater the responsibility, you must control the lock and unlock, otherwise it will lead to disaster.

5, and the combination of condition class.

6, 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 this method:

1, first new one instance

Static Reentrantlock r=New reentrantlock ();

2, lock

R.lock () or r.lockinterruptibly ();

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. To add a little bit of knowledge here, finally can be trusted: After testing, even if the execution of the statement in the outofmemoryerror,finally block can be guaranteed.

Reentrantreadwritelock

Reentrant read-write lock (an implementation of a read-write lock)

New== Lock.writelock ();

Both have lock,unlock methods. Write, write and read mutually exclusive; Read and read are not mutually exclusive. Efficient thread-safe code that can implement concurrent reads

4. Container class

Here is a discussion of the more commonly used two:

    • Blockingqueue

    • Concurrenthashmap

Blockingqueue

Blocks the 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 studying

Blockingqueue adds the ability to multi-threaded collaboration based on the queue:


Blockingqueue


In addition to the traditional queue function (two columns to the left of the table), blocking interface offers and poll that block the interface put and take, with the timeout feature. 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:

Arraylistblockingqueue

Linkedlistblockingqueue

Delayqueue

Synchronousqueue

Concurrenthashmap


Efficient thread-safe hash map. Please compare Hashtable, Concurrenthashmap, HashMap

5. Management class

The concept of 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 Threadmxbean


Threadpoolexecutor


If you do not understand this class, you should understand the aforementioned executorservice, it is very convenient to open a thread pool of your own:

Executorservice e = executors.newcachedthreadpool ();     = executors.newsinglethreadexecutor ();     = Executors.newfixedthreadpool (3);     // The first is a variable-size thread pool that allocates threads    according to the number of tasks . // The second is a single thread pool, equivalent to Fixedthreadpool    (1) // The third type is a fixed-size thread pool.     // and then run    E.execute (new Myrunnableimpl ());

This class is implemented internally through Threadpoolexecutor, which helps to understand the management of the thread pool, which is essentially a variety of implementation versions of the Threadpoolexecutor class. See Javadoc:

Threadpoolexecutor parameter explanation


Translation:


Corepoolsize: The pool inline initial and minimum values, even if it is idle, will keep the number of threads.


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. Wait status before recycling


Unit


Time units, you can use Timeunit instances, such as Timeunit.milliseconds
WorkQueue: The waiting place for the task (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.

Multithreading in Java you just have to read this one.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.