About the experience of using await and signalall in Java sync locks __java

Source: Internet
Author: User

When you use lock to ensure thread synchronization, you use the condition object to keep the thread in alignment. The condition instance is bound to a lock object, using the method of the lock Object Newcondition () to obtain an instance of condition. Condition provides the following three ways to reconcile synchronization of different threads:

1, await (): Causes the current thread to wait until the other thread calls the condition's signal () or Signalall () method to wake the thread.

2, Signal (): Wakes up a single thread waiting on this lock object.

3, Signalall (): Wakes all threads waiting on this lock object.

I encountered the problem of thread synchronization using await () and Signalall () when I was programming an exercise in the multithreaded chapter of the second edition of the Crazy Java Handout (pristine). In the web search, the reason is that I have misunderstood the await () method caused by error. The topic is as follows: Write 2 threads, one thread prints 1-52, another thread prints A-Z, the print order should be 12a34b56c ... 5152Z, need to use multithreading communication knowledge to solve.

Attach the code that eventually works correctly, plus the comments that you made at the beginning.

1, Printtask

Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;

Import Java.util.concurrent.locks.ReentrantLock; public class Printtask<t> implements Runnable {private list<t> charList = new arraylist<> ();//queue to print.		The generic private int period is used here because the print item contains both characters and incrementing numbers;	The number of each print private int priority;		Priority, that is, the print order in multiple queues private int total;		Total number of print queues public static int sequence = 0;		The currently printed queue serial number private static final lock lock = new Reentrantlock (); Because the sequence that needs to be locked is a class member, a static lock is created to ensure that different thread instances of that class can perceive signalall () private static final Condition Condition =	Lock.newcondition (); Class condition member//private final lock lock = new Reentrantlock ();-----------> When Lock and condition are not defined with static,	Because different threads are different instances,//private final Condition Condition = lock.newcondition () between each other; Unable to perceive the signalall () emitted by other classes, causing threads to wait between each other but unable to get response public printtask (list<t> charList, int period, int priority, int total){this.charlist = charList;
		This.period = period;
		This.priority = priority;
	This.total = total;
		public void Run () {iterator<t> iter = Charlist.iterator (); while (true) {Lock.lock ()//Lock try {if (sequence% total = priority) {for (int i = 0; i < period; i+
						+) {if (Iter.hasnext ()) {System.out.print (Iter.next ());
						} else {break;
					}} ++sequence;	Condition.signalall (); 
			Other instances of this class can accept the await () method of the Signalall () method} else {condition.await (),//class member condition, which informs all instances of the class that they are aware of Signalall ()}
			catch (Exception ex) {ex.printstacktrace ();
			finally {Lock.unlock ();
 }
		}
	}
}

2, the main program Printaz.java

Import java.util.ArrayList;
Import java.util.List;

public class Printaz {
	final static int total = 2;
	public static void Main (string[] args) {
		//Generate a list of numbers 1-52
		list<integer> numbers = new arraylist<> ();
		for (int i = 1; I <= i++) {
			numbers.add (i);
		}
		Generate Alphabetical List A
		-Z list<character> chars = new arraylist<> ();
		for (char i = ' A '; I <= ' Z '; i++)
		{
			chars.add (i);
		}
		Printtask (print queue, print length, order, queue totals) 
		printtask<integer> task1 = new Printtask<> (numbers, 2, 0, total); c17/>printtask<character> task2 = new Printtask<> (chars, 1, 1, total);
		New Thread (Task1). Start ();
		New Thread (Task2). Start ();
	}
}

When you define lock and condition as instance member variables, the results of the operation are as follows:

12A
When lock and condition are members of a class, the results of the operation are as follows:

12a34b56c78d910e1112f1314g1516h1718i1920j2122k2324l2526m2728n2930o3132p3334q3536r3738s3940t4142u4344v4546w4748x4950y5152z


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.