Java multithreading look at a piece enough!

Source: Internet
Author: User
Tags sleep thread class volatile
Primer

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

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 >= max_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 (); Inform the waiting producer to 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

Related Article

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.