Java Multithreading and concurrent Applications-(9)-Lock lock+ Conditional blocking Conditon implement thread synchronous communication __java

Source: Internet
Author: User
Tags finally block mutex

A. Lock can be used instead of the Synchronized keyword to implement the mutex function. Use the following methods:

Lock L = ...;
     L.lock ();
     try {
         //access the resource protected by this lock
     } finally {
         l.unlock ();
     }

It is to be noted that.

1. One or more methods that require mutual exclusion use the same mutex.

2. In the lock-contained code block, use the finally block to release the lock.

Two. The await method of condition (note not the Wait method) replaces the wait method in traditional communication, and the corresponding signal method replaces notify.

When we judge the condition of traditional communication, we use while instead of if to make the conditional judgment, it is for false awakening. So what is False awakening?

False Awakening namely: we require the AB method to be executed sequentially, there are 5 threads executing a, 5 threads executing B, if a moment all a waits, when the A1 is awakened, and executes the code, it calls the Notify method, which is intended to wake the B module execution thread, but because AB common a lock, So it is possible to wake up a, that is, to wake up the code that should not be executed, which is false awakening.

So we use the while condition, and even if we wake up, we'll do a conditional interpretation so that the code that's being spoofed will wait again.

This requires programmers to control the error of avoiding false awakening. and lock and condition help us solve the problem. A lock can have multiple condition inside. Then the same lock can be multiple condition implementation modules

The switch between, as in the example above, after A1, through B corresponding condtion.signal can only wake up b corresponding thread. We can look at the example in the condition API, the simple implementation of blocking queues:

First we look at the traditional communication technology to achieve a simple blocking queue, what is the disadvantage.

Package Com.lipeng;


Import Java.util.Random;
	public class BoundedBuffer1 <t>{private object[] objs=new object[100];
	private int length; private int putindex=0;//holding pointer private int getindex=0;//pointer/** * Storing elements, from beginning to end, again and again * @param t/public Synchroniz
		Ed void put (t) {//If it is already full, wait.
		while (length==objs.length)//If n threads wait here, after one of the threads is awakened, execute the following code, 35 lines this.notify The intention is to wake the thread to fetch the data, but in fact it may wake the stored thread.
			{try {this.wait ();
			catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }} objs[putindex]=t;  Inserts the element length++ at the end of the team;
		Length plus 1, putindex++;
			if (putindex==objs.length) {//notice is not full before starting from the beginning, but hold the pointer to the end of the team and start from scratch.
		putindex=0;
		
	} this.notify ();
	 /** * Take element, take from beginning to end, in so repeated.
			* @return */public synchronized T get () {while (length==0) {try {this.wait ();
			catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
		}} t t= (t) Objs[getindex];
		length--; Getindex++;
		if (getindex==objs.length) {getindex=0;
		} this.notify ();
	return t; public static void Main (string[] args) {final boundedbuffer1<integer> bb=new boundedbuffer1<integer> ()
		; Runnable getrun=new Runnable () {@Override public void run () {for (int i=0;i<10;i++) {synchronized (BB)
						{//Here plus synchronized just to keep the reading data and print data intact, do the demo with an Integer data=bb.get ();
					System.out.println (Thread.CurrentThread (). GetName () + "read element------" +data);
		}
					
				}
			}
		}; Runnable putrun=new Runnable () {@Override public void run () {for (int i=0;i<10;i++) {Synchroni
						Zed (BB) {//here plus synchronized just to keep the data and print data intact, do the demo with an Integer data=new Random (). Nextint (100);
						Bb.put (data);
					System.out.println (Thread.CurrentThread (). GetName () + "put---------------------------" +data);
		}
				}
			}
		};
		System.out.println ("***********************"); for (int i=0;i<10;i++) {new Thread (Getrun). Start ();
		New Thread (Putrun). Start ();





















 }
	}
}

Let's look at how condition helped us to achieve it.

Package Com.lipeng;
Import Java.util.Random;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;


Import Java.util.concurrent.locks.ReentrantLock;
	public class BoundedBuffer2 <t>{private object[] objs=new object[100];
	private int length;
	private int putindex=0;//save pointer private int getindex=0;//fetch pointer private Lock lock=new reentrantlock (); Private Condition putcon=lock.newcondition ()//Storage conditions Private Condition getcon=lock.newcondition ();/Take conditions/** * store elements, from
			Head to tail, repeat from beginning to end * @param t/public void put (T t) {try {lock.lock ();
			If it's full, wait.
			while (length==objs.length)//If n threads wait here, after one of the threads is awakened, execute the following code, 35 lines this.notify The intention is to wake the thread to fetch the data, but in fact it may wake the stored thread.
				{try {putcon.await ();
				catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }} objs[putindex]=t;  Inserts the element length++ at the end of the team;
			Length plus 1, putindex++;
				if (putindex==objs.length) {//notice is not full before starting from the beginning, but hold the pointer to the end of the team and start from scratch. putindex=0;
			} getcon.signal ();
		System.out.println (Thread.CurrentThread (). GetName () + "put---------------------------" +t);
		catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		}finally{Lock.unlock ();
	 }/** * Take the element, take it from beginning to end, in so repeated.
			* @return */public T get () {try {lock.lock ();
				while (length==0) {try {getcon.await ();
				catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
			}} t t= (t) Objs[getindex];
			length--;
			getindex++;
			if (getindex==objs.length) {getindex=0;
			} putcon.signal ();
			System.out.println (Thread.CurrentThread (). GetName () + "read element------" +t);
		return t;
			catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		return null;
		}finally{Lock.unlock (); } public static void Main (string[] args) {final boundedbuffer2<integer> bb=new Boundedbuffer2<integer&gt
		;(); Runnable Getrun=neW Runnable () {@Override public void run () {for (int i=0;i<10;i++) {bb.get ();
		}
			}
		}; Runnable putrun=new Runnable () {@Override public void run () {for (int i=0;i<10;i++) {Integer D
					Ata=new Random (). Nextint (100);
				Bb.put (data);
		}
			}
		};
		System.out.println ("***********************");
			for (int i=0;i<10;i++) {new Thread (Getrun). Start ();
		New Thread (Putrun). Start ();





















 }
	}
}

Precautions:

Lock (including read-write lock) +condition looks more object-oriented and seems to improve performance * (because I haven't verified, haha) is more rigorous, but I think if the traditional communication method is sufficient, it is not necessary to use it.


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.