If you share data on a piece, multiple threads do different things, there is read and write, it is necessary to thread communication processing, in order to improve efficiency.
One, thread communication:
1, the concept of thread communication:
Thread communication refers to the interaction between threads, which is constrained by the messaging implementation of multiple threads and dispatched to each other.
2, the implementation of Java thread communication:
Java code implements multiple threads of communication based on "Wait (), notify (), Notifyall ()" for shared data.
Classic Example: problems for producers and consumers.
1), Warehouse.java
<span style= "FONT-SIZE:18PX;" >import Java.util.arraylist;import java.util.list;/** * Warehouse class, with storage goods, contact producers and consumers * @author Hanwen * */public class Warehous e {//define a collection to store the production of the product private list<string> products=new arraylist<string> ();/** * Producers produce goods and store them in warehouses */public void Addproduct (String stringname) {products.add (Stringname);//want to add products in the warehouse}/** * consumer goods */public String getproduct () {// Determine if the warehouse is empty if (!products.isempty ()) {//Fetch product from warehouse, return to consumer string stringname=products.remove (0); return stringname;} Else{system.out.println ("The warehouse is empty, please produce products in time ..."); return "";}} /** * Get stock allowance * * @return */public int getsize () {//Return stock margin returns products.size ();}} </span>
2), Customerthread.java
<span style= "FONT-SIZE:18PX;" >/** * Consumer Threading class * * @author Administrator * */public class Customerthread implements Runnable {//attribute private Warehouse WH; Warehouse object private String name; Consumer name//constructor pass parameter public customerthread (Warehouse wh, String name) {super (); this.wh = Wh;this.name = name;} Consumer product @overridepublic void Run () {while (true) {synchronized (WH) {if (wh.getsize () = = 0) {try { System.out.println (" The warehouse is empty, the consumer "+ name +" enters the waiting state ... "); wh.wait (); System.out.println ("Thread waits for end, reboot");} catch (Interruptedexception e) {e.printstacktrace ();}} else if (wh.getsize () > 0) {//Take away goods, String Stringname = Wh.getproduct (); SYSTEM.OUT.PRINTLN ("consumer" + name + "Take away Product" + Stringname);}} try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();}}}} </span>
3), Productthread.java
<span style= "FONT-SIZE:18PX;" >import Java.util.random;public class Productthread implements Runnable {//define a warehouse object private Warehouse wh;// Construction method with parameters public Productthread (Warehouse wh) {super (); this.wh = WH;} /** * Started production of products */@Overridepublic void run () {while (true) {//automatic random production of product string stringname = "P" + (New Random ()). Nextint (1000 Synchronized (WH) {//Put the product into the warehouse wh.addproduct (Stringname);//Prompt Information System.out.println ("The warehouse has been deposited goods" + stringname);//wake-up thread , let him continue to execute//wh.notify (); Wh.notifyall ();} try {//sleep for a Thread.Sleep,} catch (Interruptedexception e) {e.printstacktrace ();}}} </span>
4), Testdemo.java
<span style= "FONT-SIZE:18PX;" >/** * Test class * @author Administrator * */public class Testdemo {public static void main (string[] args) {//Instantiate warehouse object Warehou Se wh=new Warehouse ();//Instantiate producer Object Productthread pt=new productthread (WH);//Instantiate consumer object Customerthread ct=new Customerthread (WH, "xiaoming"); Customerthread ct1=new customerthread (WH, "Floret"); Customerthread ct2=new customerthread (WH, "small grey ash"); Customerthread ct3=new customerthread (WH, "Small Fei Fei");//Build thread class to package thread T=new thread (PT); Thread t2=new thread (CT); Thread t3=new thread (CT1); Thread t4=new thread (CT2); Thread t5=new thread (CT3);//Start thread T.start (); T2.start (); T3.start (); T4.start (); T5.start ();}} </span>
3. Wait (), notify (), Notifyall () method:
①, Final void notify () wakes a single thread waiting on this object monitor
②, Final void Notifyall () wakes up all the threads waiting on this object monitor
③, Final void Wait () throws interruptedexception causes the current thread to wait until another thread calls this object's notify ()
method or Notifyall () method
④, Final void wait (long timeout) throws interruptedexception causes the current thread to wait until the other thread calls this pair
The Notify () method or the Notifyall () method, or more than the specified amount of time.
⑤, Final void wait (long timeout, int nanos) throws interruptedexception causes the current thread to wait until the other
The thread calls this object's notify () method or the Notifyall () method, or some other thread interrupts the current thread, or has exceeded a certain actual
International Time Burden.
The ⑥, Wait (), and Notify () methods, including all of the methods described above, are the final methods of the Object class, so each class has the method by default. To ensure the function of Wait () and notify (), the mutex must be obtained before execution, i.e. must be used with synchronized.
if the lock object for synchronized is obj, the correct use of wait and notify is obj.wait () and obj.notify ().
4. The difference between sleep () and Wait ():
Sleep ()
Wait ()
Propertiesmethod of the static method of the Thread object
function Let this thread go to sleep let this thread go to the waiting state
Whether releasing a sync lock does not release the synchronization will release the synchronization
5. Thread Deadlock:
①, thread deadlock refers to two threads that hold each other's shared resources dependent on each other, causing infinite blocking.
②, the root cause of deadlocks, is the inappropriate use of the "synchronized" keyword to manage thread access to specific objects.
③, how to resolve a deadlock:
let the thread hold a separate resource.
try not to use nested synchronized statements.
6. Thread state transitions:
Thread Status Introduction
1) New State (new): Use the new keyword to create a thread object that is only allocated memory;
2), operational status (Runnable): Threads have the ability to gain CPU time slices. The following are the scenarios in which threads enter the operational state:
①, Thread Start () method is called;
②, the current thread sleep (), the other thread join () end, waiting for user input completed;
③, a thread obtains the object lock;
④, the current thread has run out of time slices, calling the yield () method of the current thread.
3), running State (Running): Executes the Run method, at which point the thread obtains the CPU time slice;
4), blocking state (Blocked): The thread suspends operation due to certain events that give up CPU usage. Until the thread is re-entered to run
state, only chance go to the running state. The blocking states are divided into the following types:
①, synchronous blocking – the thread obtains a synchronous lock, and if it is occupied by another thread, the thread is placed in the lock pool queue.
②, waiting for blocking – the thread executes the wait () method, and the thread is placed in the wait queue.
③, other blocking – the thread executes sleep () or join () or makes an I/O request.
5) , death Status (Dead): Run, Main () method execution end, or due to an exception exit the run () method, the thread into the death
state, no longer The second resurrection.
Multithreading Knowledge point 3