Java thread communication and java thread Communication

Source: Internet
Author: User

Java thread communication and java thread Communication

Thread communication is used to ensure the coordinated running of threads. Generally, thread communication needs to be considered during thread synchronization.

1. Traditional thread Communication

The Objeclt class usually provides three methods:

Wait () causes the current thread to wait and releases the lock of the synchronization monitor until other threads call the notify () or notifyAll () method of the synchronization monitor to wake up the thread.

Y () to wake up the threads waiting on this synchronization monitor. If there are multiple threads, either of them will wake up.

NotifyAll () wakes up all threads waiting on this synchronization monitor. After these threads compete for resources by scheduling, a thread obtains the Lock of this synchronization monitor and then runs it.

These three methods must be called by the synchronization monitor object. There are two scenarios:

When synchronizing methods, because the synchronization monitor is the this object, you can directly call these three methods.

Example:

Public class SyncMethodThreadCommunication {static class DataWrap {int data = 0; boolean flag = false; public synchronized void addThreadA () {if (flag) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} data ++; System. out. println (Thread. currentThread (). getName () + "" + data); flag = true; y ();} public synchronized void addThreadB () {if (! Flag) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} data ++; System. out. println (Thread. currentThread (). getName () + "" + data); flag = false; Policy () ;}} static class ThreadA extends Thread {private DataWrap data; public ThreadA (DataWrap dataWrap) {this. data = dataWrap ;}@ Override public void run () {for (int I = 0; I <10; I ++) {data. addThreadA () ;}} static class ThreadB extends Thread {private DataWrap data; public ThreadB (DataWrap dataWrap) {this. data = dataWrap ;}@ Override public void run () {for (int I = 0; I <10; I ++) {data. addThreadB () ;}} public static void main (String [] args) {// implement two threads to add one to the data in turn and DataWrap dataWrap = new DataWrap (); new ThreadA (dataWrap ). start (); new ThreadB (dataWrap ). start ();}}

 

When synchronizing code blocks, you must use the monitor object to call these three methods.

Example:

Public class SyncBlockThreadComminication {static class DataWrap {boolean flag; int data;} static class ThreadA extends Thread {DataWrap dataWrap; public ThreadA (DataWrap dataWrap) {this. dataWrap = dataWrap ;}@ Override public void run () {for (int I = 0; I <10; I ++) {synchronized (dataWrap) {if (dataWrap. flag) {try {dataWrap. wait ();} catch (InterruptedException e) {e. printStackTrace ();}} DataWrap. data ++; System. out. println (getName () + "" + dataWrap. data); dataWrap. flag = true; dataWrap. notify () ;}}} static class ThreadB extends Thread {DataWrap dataWrap; public ThreadB (DataWrap dataWrap) {this. dataWrap = dataWrap ;}@ Override public void run () {for (int I = 0; I <10; I ++) {synchronized (dataWrap) {if (! DataWrap. flag) {try {dataWrap. wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} dataWrap. data ++; System. out. println (getName () + "" + dataWrap. data); dataWrap. flag = false; dataWrap. notify () ;}}} public static void main (String [] args) {// implement two threads to add one to the data in turn and DataWrap dataWrap = new DataWrap (); new ThreadA (dataWrap ). start (); new ThreadB (dataWrap ). start ();}}

2. Use Condition to control thread Communication

When the Lock object is used to ensure synchronization, the Condition object is used to ensure coordination.

Example:

Import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock; import com. sun. media. sound. RIFFInvalidDataException; import javafx. scene. chart. pieChart. data; public class SyncLockThreadCommunication {static class DataWrap {int data; boolean flag; private final Lock lock = new ReentrantLock (); private final Condition condition = lock. NewCondition (); public void addThreadA () {lock. lock (); try {if (flag) {try {condition. await ();} catch (InterruptedException e) {e. printStackTrace () ;}} data ++; System. out. println (Thread. currentThread (). getName () + "" + data); flag = true; condition. signal ();} finally {lock. unlock () ;}} public void addThreadB () {lock. lock (); try {if (! Flag) {try {condition. await ();} catch (InterruptedException e) {e. printStackTrace () ;}} data ++; System. out. println (Thread. currentThread (). getName () + "" + data); flag = false; condition. signal ();} finally {lock. unlock () ;}} static class ThreadA extends Thread {DataWrap dataWrap; public ThreadA (DataWrap dataWrap) {this. dataWrap = dataWrap;} @ Override public void run () {for (int I = 0; I <10; I ++) {dataWrap. addThreadA () ;}} static class ThreadB extends Thread {DataWrap dataWrap; public ThreadB (DataWrap dataWrap) {this. dataWrap = dataWrap;} @ Override public void run () {for (int I = 0; I <10; I ++) {dataWrap. addThreadB () ;}} public static void main (String [] args) {// implement two threads to add one to the data in turn and DataWrap dataWrap = new DataWrap (); new ThreadA (dataWrap ). start (); new ThreadB (dataWrap ). start ();}}

The await (), singal (), and singalAll () of the Condition object correspond to the wait (), Policy (), and policyall () methods respectively.

3. Use blocking queue BlockingQueue to control thread Communication

BlockingQueue is a sub-interface of the Queue interface, which is mainly used for thread communication. It has a feature: When the producer thread tries to put an element into BlockingQueue, if the Queue is full, the thread is blocked. When the consumer thread tries to extract elements from BlockingQueue, if the queue is empty, the thread is blocked. These two features correspond to two blocking methods, put (E) and take ()

Example:

Import java. util. concurrent. arrayBlockingQueue; import java. util. concurrent. blockingQueue; public class extends {static class DataWrap {int data;} static class ThreadA extends Thread {private BlockingQueue <DataWrap> blockingQueue; public ThreadA (BlockingQueue <DataWrap> blockingQueue, String name) {super (name); this. blockingQueue = blockingQueue;} @ Override public void run () {for (int I = 0; I <100; I ++) {try {DataWrap dataWrap = blockingQueue. take (); dataWrap. data ++; System. out. println (getName () + "" + dataWrap. data); sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}}} static class ThreadB extends Thread {private BlockingQueue <DataWrap> blockingQueue; private DataWrap dataWrap; public ThreadB (BlockingQueue <DataWrap> blockingQueue, DataWrap dataWrap, String name) {super (name); this. blockingQueue = blockingQueue; this. dataWrap = dataWrap;} @ Override public void run () {for (int I = 0; I <100; I ++) {try {dataWrap. data ++; System. out. println (getName () + "" + dataWrap. data); blockingQueue. put (dataWrap); sleep (1000);} catch (InterruptedException e) {e. printStackTrace () ;}}} public static void main (String [] args) {// implement two threads to add one to the data in turn and DataWrap dataWrap = new DataWrap (); blockingQueue <DataWrap> blockingQueue = new ArrayBlockingQueue <> (1); new ThreadA (blockingQueue, "Consumer "). start (); new ThreadB (blockingQueue, dataWrap, "Producer "). start ();}}

BlockingQueue has five implementation classes:

ArrayBlockingQueue array-based BlockingQueue queue

BlockingQueue Queue Based on linked list

The elements in PriorityBlockingQueue must implement the Comparable interface. The elements are sorted by Comparator.

The SynchronousQueue synchronization queue requires that the access operations to this queue must be performed alternately.

The DelayQueue set elements must implement the Delay interface. The elements in the queue are sorted according to the return values of the Delay interface method getDelay.

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.