Java multi-thread communication problem Extension

Source: Internet
Author: User

Java multi-thread communication problem Extension

What is inter-thread communication?

Threads need to communicate with each other to accomplish the same task. Simply put, if you want to do this, I also want to do it. We both want to communicate with each other, to do this together, the synchronization of the common task must be implemented through the synchronization lock. Each object instance has its own lock, when a thread wants to process this task, it must obtain the lock. The release and acquisition of locks between threads are implemented through the wait ()/notify () method in the Object class. The wait () method is to release the lock for the thread that currently has the lock as to the wait state, while the notify () method is to wake up other threads to make them qualified for execution and come to get the lock, the execution right is obtained after the lock is obtained.

It must be noted that the wait () method will have a lock only when it is out of the synchronization region, and the Thread in the synchronization region is the same. the sleep () method only enables the thread to sleep during the specified time period.Instead of releasing the lock


There are two main ways to communicate between threads:

1. Shared Memory

I wrote it at the first time and wrote a simple

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() {while(true){synchronized (this) {System.out.println(Thread.currentThread().getName()+"--:--"+(++data));}}}}public Thread getThread(){return new Thread(new Inside());}}


Ps: Shared Memory communication mode is unstable and sometimes causes problems.


2. Pipeline Flow

The communication between threads is implemented through the pipeline stream, which is mainly to connect the pipeline stream 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);pout.write(x);} catch (Exception e) {e.printStackTrace();}}}}}}class Customer implements Runnable{private PipedInputStream pin = null;public Customer(PipedInputStream pin) {this.pin = pin;}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) {PipedInputStream 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 stream is blocking, data synchronization and concurrency may fail.


The problem of inter-thread communication can lead to multi-producer and multi-consumer problems.

There are two solutions to multiple producers and consumers:

1. Adopt a mechanism to synchronize producers/consumers (commonly used and highly efficient)

2. Pipeline stream

To solve the synchronization problem, it is generally the synchronized function or code block + while + policyall method,The emergence of interface Lock enables more flexible operations and supports multiple listeners to implement more extensive Lock operations.


The Lock method is demonstrated 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 goods corresponds to a serial 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 considerations: The objects involved, producers, consumers, goods, warehouses * producers, and consumers correspond to the same warehouse, the warehouse corresponds 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 storage SIZE of the Repository. private Lock lock = new ReentrantLock (); // creates the lock private Condition Pro_lock = Lock. newCondition (); // create the producer monitor private Condition Cus_lock = lock. newCondition (); // create consumer monitor private int putnum = 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); // latency 100 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); // latency 100 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 proThread2 = new Thread (p1); Thread cusThread1 = new Thread (c ); // consumer Thread cusThread2 = new Thread (c1); proThread1.start (); cusThread1.start (); proThread2.start (); cusThread2.start ();}}








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.