Ways to communicate between threads

Source: Internet
Author: User
Tags require sleep

Objective
Speaking of communication between threads: According to my understanding, there are two main types.
1. Is through the sharing of variables, between the threads through this variable for collaborative communication;
2. Through the queue (which is essentially the same block of memory shared between threads) to implement consumer and producer patterns to communicate;

1. How variables are shared across threads

It is necessary to say wait (), notify (), and Notifyall () These three methods are all methods of object, so all classes can inherit these three methods;
The wait () method causes the current thread to wait until another thread calls the Notify () or Notifyall () method. The Notify () method wakes up a thread that waits for a lock on the current object. The Notifyall () is the name of the wake-up call, and the Wait () and notify () methods require that the thread has acquired the lock on the object at the time of invocation, so calls to both methods need to be placed in the synchronized method or synchronized block.

Let's take a look at the following example.
-Demo with Wait () and Notifyall () to add and subtract between multiple threads

Package com.zeng.awaitNotify;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit; /** * By sharing a variable, wait () +notify () to practice the communication * Wait () and notify () methods require that the thread has acquired the lock on the object at the time of the call,
 Therefore, the calls to both methods need to be placed in the Synchronized method or the synchronized block. * * No problem for two threads * when there are more threads, you must use Notifyall () * @author Leo-zeng * */public class Numberholder {private

    int number;
                Public synchronized void Increase () {while (number!=0) {try {//If Nuber does not wait 0 o'clock
            Wait ();
            } catch (Interruptedexception e) {e.printstacktrace ();
        }}//Can execute here, the description has been awakened, and is 0 number + +;
        SYSTEM.OUT.PRINTLN ("I Want to Increment:" +number);
    Notifies the waiting thread of Notifyall ();
                Public synchronized void decrease () {while (number ==0) {try {//if equal to zero waits for wake
            Wait ();
    } catch (Interruptedexception e) {            E.printstacktrace ();
        }}//Can execute here, the description has been awakened, and is not 0 number--;
        SYSTEM.OUT.PRINTLN ("I Want to Decrement:" +number);
    Notifyall ();

        } public static void Main (string[] args) {Executorservice pool = Executors.newfixedthreadpool (10);

        Numberholder holder =new Numberholder ();
        Implementation of Task Pool.execute (new Increasethread (holder));

        Pool.execute (new Decreasethread (holder));
        Pool.execute (new Increasethread (holder));

        Pool.execute (new Decreasethread (holder));
        Pool.shutdown ();
        try {pool.awaittermination (300,timeunit.seconds);
        } catch (Interruptedexception e) {e.printstacktrace ();

    }}}/** * Cumulative class * @author Leo * */class Increasethread extends thread{private Numberholder numberholder;
    Public Increasethread (Numberholder numberholder) {This.numberholder =numberholder; } @Override public void Run (){for (int i = 0; i < i++) {//each time there is not much delay try {thread.sleep (long) M
            Ath.random () *1000);
            } catch (Interruptedexception e) {e.printstacktrace ();
        }//Perform new Operation Numberholder.increase ();

    }}} class Decreasethread extends thread{private numberholder holder;
    Public Decreasethread (Numberholder holder) {This.holder =holder; 
                } @Override public void Run () {for (int i = 0; I <20; i++) {//Every time there is not much delay try {
            Thread.Sleep ((Long) math.random () *1000);
            } catch (Interruptedexception e) {e.printstacktrace ();
        }//Perform decrement function holder.decrease (); }
    }
}

Note that it is possible to use while without if because it is guaranteed to be multi-threaded, to eliminate the possibility that the accumulation/decrement may occur multiple times. use Lock.newcondition (). await () and signal () methods to interact between threads
In addition to using wait and notify in the synchronized code block above, In fact, in the Java.util.concurrent package, there are two very special tool classes, condition and reentrantlock, can also be implemented in the same thread of interactive collaboration.
Reentrantlock (re-entry lock) and condition I do not want to elaborate here, interested can go to see some JDK source code. Here's an introduction to the await () and signal () methods in condition;
We'll look at the demo here and then explain the meaning of the two:

Package com.zeng.awaitNotify;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.TimeUnit;
Import java.util.concurrent.locks.Condition;

Import Java.util.concurrent.locks.ReentrantLock;

    /** * by sharing variables * @author Leo-zeng * */public class Resource {private int i;

    Private final Reentrantlock lock = new Reentrantlock ();

    Private final Condition Condition =lock.newcondition ();
            public void incr () {try {//Lock lock.lock ();
            while (i!=0) {//stop, wait for wake-up Signal condition.await ();
            }//Description has been obtained can be used signal i++;
            System.out.println ("Increment:" +i);
        Add signal to other condition.signalall ();
        } catch (Interruptedexception e) {e.printstacktrace ();
        }finally{//Unlock lock.unlock ();
     }} public void Decr () {try {//Lock       Lock.lock ();
            while (i==0) {//halt, wait for the signal to increment over there condition.await ();
            }//i!=0 get the signal over there i--;
            System.out.println ("Descending:" +i);
        Add signal to other condition.signalall ();
        } catch (Interruptedexception e) {e.printstacktrace ();
        }finally{//Unlock lock.unlock (); }} public static void Main (string[] args) {Executorservice ThreadPool = Executors.newfixedthreadpool (10
        );

        Resource ss = new Resource ();
        Threadpool.submit (New Incrthread (ss));
        Threadpool.submit (New Decrthread (ss));
        Threadpool.submit (New Incrthread (ss));
        Threadpool.submit (New Decrthread (ss));
        Threadpool.shutdown ();
        try {threadpool.awaittermination (300,timeunit.seconds);
        } catch (Interruptedexception e) {e.printstacktrace (); }}} class Incrthread extends Thread{private Resource Resource;
    Public Incrthread (Resource Resource) {this.resource = Resource;
                } @Override public void Run () {for (int i = 0; I <20; i++) {//pause per second try {
            Thread.Sleep (500);
            } catch (Interruptedexception e) {e.printstacktrace ();
        } resource.incr ();

    }}} class Decrthread extends thread{private Resource Resource;
    Public Decrthread (Resource Resource) {this.resource = Resource;
                } @Override public void Run () {for (int i = 0; I <20; i++) {//pause per second try {
            Thread.Sleep (500);
            } catch (Interruptedexception e) {e.printstacktrace ();
        } RESOURCE.DECR (); }
    }
}

From the demo can see the await () method, is to first give a (cumulative) line loads lock, enter await will let the thread sleep, wait for signal signal to wake up, this is a line threads unlocked will go to sleep, run b thread; b line Chengxianga lock then decrement, A value of 0 will also take place and sleep, then unlock and lock to a. To communicate in this way.

2. Thread communication through queues here is the Java.util.concurrent packet linkedblockingqueue for inter-thread interaction;
The Java.util.concurrent.LinkedBlockingQueue is a one-way linked list, a range of arbitrary (in fact, bounded), FIFO blocking queue. The access and removal operations are performed on the team head, and the additions are made at the end of the queue and protected with different locks, and only two locks are locked at the same time if the operation may involve multiple nodes. This is achieved by sharing information about a queue to enable producers and consumers

Package com.zeng.awaitNotify;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.LinkedBlockingQueue;
Import Java.util.concurrent.TimeUnit; /** * Build inter-thread communication through Linkedblockingqueue * @author Leo-zeng * */public class Linkedblockingqueuetest {public static V
        OID Main (string[] args) {linkedblockingqueue<string> queue = new linkedblockingqueue<string> ();
        Executorservice ThreadPool = Executors.newfixedthreadpool (10);
        Threadpool.execute (new Producer (queue));


        Threadpool.execute (new Consumer (queue));
            if (!threadpool.isshutdown ()) {Threadpool.shutdown ();
            try {threadpool.awaittermination (timeunit.seconds);
            } catch (Interruptedexception e) {e.printstacktrace ();

    }}}} class Producer extends thread{private linkedblockingqueue<string> queue; Public Producer (LinkedBlockingqueue<string> queue) {This.queue =queue; @Override public void Run () {for (int i = 0; i <; i++) {System.out.println ("produced:" +i
            );
                try {thread.sleep (100);
            Queue.put (New String ("Producer:" +i));
            } catch (Interruptedexception e) {e.printstacktrace ();

    }}}} class Consumer extends thread{private linkedblockingqueue<?> queue;
    Public Consumer (linkedblockingqueue<string> q) {this.queue =q; } @Override public void Run () {while (true) {try {System.out.println ("consume
            R consumed: "+queue.take ());
            } catch (Interruptedexception e) {e.printstacktrace (); }
        }
    }
}

Resources:

1.http://www.cnblogs.com/mengdd/archive/2013/02/20/2917956.html
2.http://ifeve.com/understand-condition/
3.http://ifeve.com/juc-linkedblockingqueue/

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.