What exactly is the communication between threads?
Between the threads need through some coordination of communication, to achieve the common task of accomplishing the same, simply say, you want to do this, I also want to do this thing, we two mutual exchange, do this together, and the synchronous implementation of the common task, must pass the synchronous lock, each object instance has its own lock, When a thread wants to handle this task, it must obtain the lock. The release and fetch of locks between threads is implemented by the Wait ()/notify () method in the object class. The wait () method is to let the thread that currently owns the lock release the lock, and the Notify () method is to wake up the other thread to be eligible for execution, come over to take the lock, and get the lock before it has the execution right.
Note that it is important to ensure that the wait () method is out of sync, and that the Thread.Sleep () method for the synchronization region only causes the thread to sleep within the specified time period . without releasing the lock
There are two main ways to communicate between threads:
1. Shared memory
When I first learned it, I wrote it and wrote a simple one.
public class Main{public static void Main (string[] args) {Memorythread MyThread = new Memorythread (); Mythread.getthread (). Start (); Mythread.getthread (). Start ();}} Class Memorythread {private int data;public memorythread () {//TODO auto-generated constructor stubdata = 0;} public class Inside implements Runnable{public void Run () {when (true) {synchronized (this) {System.out.println ( Thread.CurrentThread (). GetName () + "--:--" + (++data));}}} Public Thread GetThread () {return new Thread (new Inside ());}}
PS: Shared Memory This communication mode, there is instability, sometimes problems occur
2. Pipeline Flow
The communication between threads is realized through pipeline flow, which mainly connects the pipeline to the thread.
Class Producer implements Runnable{private pipedoutputstream pout = null;public Producer (PipedOutputStream pout) { This.pout = pout;} public void Run () {int x = 1;//TODO auto-generated method Stubsynchronized (this) {while (true) {synchronized (this) {try { System.out.println ("Producer set" +x);p out.write (x);} catch (Exception e) {e.printstacktrace ();}}}}} Class Customer implements Runnable{private pipedinputstream pin = null;public Customer (pipedinputstream pin) {This.pin = P In;} public void Run () {while (true) {synchronized (this) {try {System.out.println ("Customer get" +pin.read ());} catch (Exception e) {//Todo:handle Exception}}}}}public class main{public static void Main (string[] args) {Pipedinputstr EAM pin = new PipedInputStream (); PipedOutputStream pot = new PipedOutputStream (); Try{pot.connect (PIN);} catch (Exception e) {e.printstacktrace ();} New Thread (new Producer (pot)). Start (); New Thread (New Customer (PIN)). Start ();}}
PS: Because the Read method of the pipeline flow is blocking, the synchronization and concurrency of the data can cause problems
Communication issues between threads can then be raised to multi-producer multi-consumer issues
Multi-producer Multi-consumer problem solving methods are generally divided into two kinds:
1. Use of a mechanism to achieve synchronization between producers/consumers (common, high efficiency)
2. How to use pipeline flow
solve the synchronization problem, is generally synchronized function or code block +while+notifyall way, The advent of interface lock, with more flexible operation, can support multiple listeners, so as to achieve a more extensive operation of the lock
The way to directly show lock here
Import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;/** * Created by Kevy on 14-12-01. *//** * Description: The warehouse stores the goods, each item corresponds to a number * when the warehouse is full, the producer cannot store the goods. When the warehouse is empty, the consumer cannot take the goods. * Object-oriented thinking: objects involved, producers, consumers, goods, warehouses * producers, consumers correspond to the same warehouse, warehouse corresponding to different goods */class Goods {private String name; private int num; Goods (String name,int num) {this.name = name; This.num = num; } public String GetName () {return name; } public int Getnum () {return num; }}class storehouse{public final static int SIZE = 10; Private goods[] goodses = new goods[size];//defines the warehouse storage size private Lock lock = new Reentrantlock ();//create Lock Private Condition Pro_lock = Lock.newcondition ();//create producer monitor private Condition Cus_lock = Lock.newcondition ();//create Consumer monitor private int p Utnum = 0,count = 0,takenum = 0; public void Set (Goods good) {lock.lock (); try{while (count==size) {try{ Pro_lock.await (); }catch (Exception e) {e.printstacktrace (); }} thread.sleep (100);//delay of goodses[putnum] = good; System.out.println (Thread.CurrentThread (). GetName () + "++++ production ++++" + Good.getname () +good.getnum ()); if (++putnum==size) putnum = 0; count++; Cus_lock.signal (); }catch (Exception e) {e.printstacktrace (); }finally {lock.unlock (); }} public void out () {lock.lock (); try{while (count==0) {try{cus_lock.await (); }catch (Exception e) {e.printstacktrace (); }} thread.sleep (100);//delay Goods item = Goodses[takenum]; if (++takenum==size) takenum = 0; --count; System.out.println (Thread.CurrentThread (). GetName ()+ "----consumption----" + item.getname () +item.getnum ()); Pro_lock.signal (); }catch (Exception e) {e.printstacktrace (); }finally {lock.unlock (); }}}class Producer implements runnable{private storehouse storehouse = null; Private String goodname = null; Producer (Storehouse storehouse,string goodname) {this.storehouse = storehouse; This. Goodname = Goodname; public void Run () {int NUM = 1; while (true) {Storehouse.set (new Goods (goodname,num++)); }}}class Customer implements runnable{private storehouse storehouse = null; Customer (Storehouse storehouse) {this.storehouse = storehouse; public void Run () {while (true) {storehouse.out (); }}}public class Main {public static storehouse storehouse; public static void Main (string[] args) {storehouse = new storehouse (); Runnable p = new Producer (storeHouse, "toilet paper"); Runnable P1 = new Producer (storehouse, "Java Technology-core Volume I"); Runnable C = new Customer (storehouse); Runnable C1 = new Customer (storehouse); Thread proThread1 = new Thread (p);//producer thread thread proThread2 = new Thread (p1); Thread cusThread1 = new Thread (c);//consumer thread thread cusThread2 = new Thread (c1); Prothread1.start (); Custhread1.start (); Prothread2.start (); Custhread2.start (); }}
Extension of communication problem between Java multithreading