Lock Application Thread collaboration

Source: Internet
Author: User

The internal Lock Object monitor uses the wait (), Y (), and notifyAll () Methods of the Object class for collaborative communication between threads. The Lock introduces Condition to support communication and collaboration between threads, condition provides the await (), signal (), and signalAll () methods to implement the same wait and wake-up functions as internal locks. However, unlike internal locks, one Lock can bind multiple conditions, to wake up different threads under different conditions.


The typical example of thread collaboration is producer and consumer. If the internal lock control thread is used for communication, all threads, whether the producer or consumer, are monitored by the same object. When the newly produced object is put into the consumption queue, the producer will wake up all threads, including other producers, the queue may be full, so the Awakened producer has to continue to wait for the queue, polling until a consumer is awakened to consume, and then continue. Because the Lock supports binding multiple conditions, if you use the Lock implementation, you can create a Condition for the queue when there are objects that can be consumed, and create a Condition when the queue has spaces. In this way, producers and consumers can clearly inform each other, rather than lack a clear target object in a way like an internal lock broadcast.


In short, the internal locks y () and notifyAll () will wake up any thread, regardless of whether the thread's waiting conditions have been met; condition provides the implementation of customized wake-up conditions for different types of threads to reduce unnecessary wake-up.


In addition, after testing, a thread may be awakened by some other conditions in multi-core scenarios. Therefore, the test results are not necessarily satisfactory and need to be further investigated.


Example of producer and consumer Code implemented by internal Lock and Lock:

import java.util.LinkedList;import java.util.Queue;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class TestLockCondition {    private static final int MAX_SIZE = 3;    private static final int PRODUCER_NUM = 5;    private static final int CONSUMER_NUM = 1;    private Queue<Object> queue = new LinkedList<Object>();    private volatile boolean isWorkingTime = true;    private volatile boolean isUsingLock = true;    private Lock lock = new ReentrantLock();    private Condition full = lock.newCondition();      private Condition empty = lock.newCondition();          private void produceWithLock() throws InterruptedException{        lock.lock();        try{            while(queue.size() >= MAX_SIZE){                System.out.println(Thread.currentThread().getName() + " go wait.");                full.await();                System.out.println(Thread.currentThread().getName() + " was awaken.");            }                                  queue.offer(new Object());            System.out.println(Thread.currentThread().getName() + " produce one object.");            empty.signalAll();            //empty.signal();        }        finally{            lock.unlock();        }                  }          private void consumeWithLock() throws InterruptedException{        lock.lock();        try{            while(queue.isEmpty()){                System.out.println(Thread.currentThread().getName() + " go wait.");                empty.await();                System.out.println(Thread.currentThread().getName() + " was awaken.");            }                                  queue.poll();            System.out.println(Thread.currentThread().getName() + " consume one object.");            full.signalAll();            //full.signal();        }        finally{            lock.unlock();        }                  }          private synchronized void produce() throws InterruptedException{        while(queue.size() >= MAX_SIZE){            System.out.println(Thread.currentThread().getName() + " go wait.");            wait();            System.out.println(Thread.currentThread().getName() + " was awaken.");        }                          queue.offer(new Object());        System.out.println(Thread.currentThread().getName() + " produce one object.");        //notifyAll();        notify();    }          private synchronized void consume() throws InterruptedException{        while(queue.isEmpty()){            System.out.println(Thread.currentThread().getName() + " go wait.");            wait();            System.out.println(Thread.currentThread().getName() + " was awaken.");        }                          queue.poll();        System.out.println(Thread.currentThread().getName() + " consume one object.");        //notifyAll();        notify();    }          public static void main(String[] args) throws InterruptedException {        TestLockCondition testLockCondition = new TestLockCondition();                  Thread[] producers = new Thread[PRODUCER_NUM];                  for(int i=0; i<PRODUCER_NUM; i++){            producers[i] = new Thread(testLockCondition.new Producer());            producers[i].start();        }                        Thread[] consumers = new Thread[CONSUMER_NUM];        for(int i=0; i<CONSUMER_NUM; i++){            consumers[i] = new Thread(testLockCondition.new Consumer());            consumers[i].start();        }                  TimeUnit.SECONDS.sleep(10);                  for(int i=0; i<PRODUCER_NUM; i++){            System.out.println(producers[i].getName() + " : " + producers[i].getState());            producers[i].interrupt();        }                  for(int i=0; i<CONSUMER_NUM; i++){            System.out.println(consumers[i].getName() + " : " + consumers[i].getState());            consumers[i].interrupt();        }                          testLockCondition.isWorkingTime = false;    }          private class Consumer implements Runnable{        @Override        public void run() {            try {                while(isWorkingTime){                    if(isUsingLock){                        //System.out.println(Thread.currentThread().getName() + " is using Lock.");                        consumeWithLock();                    }                    else{                        consume();                    }                                  }                          } catch (InterruptedException e) {                e.printStackTrace();            }                  }              }    private class Producer implements Runnable{        @Override        public void run() {            try {                while(isWorkingTime){                    if(isUsingLock){                        //System.out.println(Thread.currentThread().getName() + " is using Lock.");                        produceWithLock();                    }                    else{                        produce();                    }                }                          } catch (InterruptedException e) {                e.printStackTrace();            }        }              }}


This article is from "the power comes from the sincere love !" Blog, please be sure to keep this source http://stevex.blog.51cto.com/4300375/1300223

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.