Java---Multithreading and threading concepts

Source: Internet
Author: User
Tags finally block volatile

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 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. As the above code simply adds @synchronized keywords. 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 the horse: The State of the thread
    2. Internal organs Heart: The method of each object (mechanism)
    3. Chang Quan: Basic Threading Class
    4. Nine Yin Canon: Advanced Multithreading 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 () methods, the sleep () time ends or is interrupted, the join () is interrupted, and the 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 woken up and placed into the lock pool (lock blocked), Releasing a sync lock to bring the thread back to the operational state (Runnable)
    3. The line loads Sync Lock (Synchronized) for the running state enters (lock blocked pool) and 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: 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 Thread1 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 Thread1 implements Runnable {public   synchronized void Run () {          : Do Something   }}
  • Synchronized, wait, notify combination: Typical scenario producer consumer issues

    /**   * The product produced by the producer is given to the clerk */public  synchronized Void Produce ()  {      if (this.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           {              wait ();               System.out.println ("Out of stock, fetch later");          }           catch (interruptedexception e)           {              e.printstacktrace ();          }          return;      }      System.out.println ("The consumer took the first" + This.product + "products.");      this.product--;      Notifyall ();   Inform the producers waiting to be ready to produce the product.  }
    Volatile

    Multi-threaded memory model: Main Memories (memory), 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:

MyThread my = new MyThread (); My.start ();

Thread Class related methods:

The current thread can transfer CPU control to allow other ready state threads to 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 ()//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 for callable can also support the Runnable interface type. Future future = E.submit (New mycallable ()), Future.isdone ()//return true,false nonblocking future.get ()//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

The return value is booleanatomicinteger.compareandset (int expect,int update)

This method can be used to implement optimistic locking, considering the first mentioned scenario: A to B payment of 10 yuan, a deduction of 10 yuan, B to add 10 yuan. At this time c to B2 yuan, but B's plus 10 Yuan 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:

ReentrantLockReentrantReadWriteLock.ReadLockReentrantReadWriteLock.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:

Lock is more flexible, you can freely define the locking order of multiple locks (synchronized to follow the first order) 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 this method:

1. Start with a new instance

Static Reentrantlock r=new reentrantlock ();
2. Add 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) 

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. Efficient thread-safe code that can implement concurrent reads

4. Container class

Here is a discussion of the more commonly used two:

Blockingqueueconcurrenthashmap

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:

Arraylistblockingqueuelinkedlistblockingqueuedelayqueuesynchronousqueue

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 ();    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 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. 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---Multithreading and threading concepts

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.