Simulate queue (queue) using Wait () and notify ()

Source: Internet
Author: User
Tags int size

In Java multithreading, the JDK provides a wait and notify implementation control of the process, both to be used with the Synchronized keyword, and to obtain the object lock first. Wait is the release lock, notify is not releasing the lock.

As an example:

Listdemo Code:

public class listdemo{
    
    private static linkedlist<integer> list = new linkedlist<> ();
    
    public static void Add () {
        list.add (1);
    }
    
    public static int size () {return
        list.size ();
    }
}
Thread A:

public class Threada implements Runnable {
    private Object obj;
    Threada () {

    } public
    Threada (Object obj) {
        this.obj = obj;
    }

    @Override public
    Void Run () {
        try{
            synchronized (obj) {
                if (mylist.size ()!=5) {
                    SYSTEM.OUT.PRINTLN ("Wait Begin" +system.currenttimemillis ());
                    Obj.wait ();
                    SYSTEM.OUT.PRINTLN ("Wait End" +system.currenttimemillis ());}}}
        catch (Interruptedexception e) {
            e.printstacktrace ();}}}
Thread B:

public class THREADB implements runnable{
    private Object obj;
    Threadb () {

    } public
    threadb (Object obj) {
        super ();
        This.obj = obj;
    }
    @Override public
    Void Run () {
        try{
            synchronized (obj) {for
                (int i=0;i<10;i++) {
                    Mylist.add ( );
                    if (Mylist.size () ==5) {
                        obj.notify ();
                        SYSTEM.OUT.PRINTLN ("notice already issued");
                    }
                    System.out.println ("added" +i+ "element");
                    Thread.Sleep (1000);}}
        catch (Interruptedexception e) {
            e.printstacktrace ();}}}
Main method:

public class Main {public
    static void Main (string[] args) {
        try{
            Object obj = new Object ();
            New Thread (New Threada (obj)). Start ();
            Thread.Sleep (1000);
            New Thread (New threadb (obj)). Start ();
        catch (Interruptedexception e) {
            e.printstacktrace ();}}}
Run Result:


Thread A waits until the end of thread B execution to continue, visible wait releases the lock, and notify does not release the lock. use wait and notify to simulate queues:

Use wait and notify to implement blocking placement and removal (first-in first out), train of thought: the maximum length of the queue is 5; When an element is added, the queue size is judged to be 5, if it is waiting to be added, and the element is removed to determine whether the queue size is 0, and if so, wait for removal. The implementation code is as follows:

public class Myqueue {//Storage of data with a thread-safe list The private final linkedlist<object> list = new linkedlist<> ()
    ; Private final Atomicinteger count = new Atomicinteger ();
    Counter private final int maxSize = 5;

    Private final int minsize = 0;

    Initialize lock object Private Final Object lock = new Object (); /** * Put method */public void put (Object obj) {synchronized (lock) {while (count.get () = = m
                axsize) {try{lock.wait ();
                }catch (interruptedexception e) {e.printstacktrace ();
            } list.add (obj);
            In Atomicinteger, getandincrement the current value by an atomic method of 1.
            Count.getandincrement ();
            System.out.println ("element" +obj+ "added");
        Lock.notify ();
        }/** * Get method/public object get () {Object temp;
       Synchronized (lock) {while (Count.get () ==minsize) {         try {lock.wait ();
                }catch (interruptedexception e) {e.printstacktrace ();
            } count.getanddecrement ();
            Gets the first element of the list and returns TEMP = List.removefirst ();
            System.out.println ("element" +temp+ "removed");
        Lock.notify ();
    return to temp;
        public static void Main (string[] args) throws interruptedexception{final Myqueue myqueue = new Myqueue ();
        Initqueue (Myqueue); Thread Th1 = new Thread (new Runnable () {@Override public void run () {Myqueue.put
                ("F");
            Myqueue.put ("G");

        }
        });
                    Thread Th2 = new Thread (new Runnable () {@Override public void run () {try{
                    Thread.Sleep (1000);
                    Myqueue.get ();
                    Thread.Sleep (1000); MyquEue.get ();
                }catch (interruptedexception e) {e.printstacktrace ();
        }
            }
        });
        Th1.start ();
        Thread.Sleep (1000);
    Th2.start ();
    private int size () {return count.get ();
        private static void Initqueue (Myqueue myqueue) {myqueue.put ("a");
        Myqueue.put ("B");
        Myqueue.put ("C");
        Myqueue.put ("D");
        Myqueue.put ("E");
    System.out.println ("Current number" +myqueue.size ()); }
}
Run Result:


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.