Concurrent programming this aspect of previous attention to a relatively small, bad to fill, recommend a good website: Concurrent Programming Network-ifeve.com, the above are all kinds of Daniel original or compiled concurrent programming articles.
Come to learn semaphore today (semaphore), literally, do not know what this thing is doing, borrowing the Concurrency tool Class (iii) control the number of concurrent threads semaphore The example of traffic red and green lights in the article to understand:
A 4-lane main road, assuming 100 meters long, each vehicle assumes a length of 10 meters (considering the front and rear distance), that is, the road is full of load operation, the maximum can only accommodate the (100/10) = 40 cars, if there are 120 cars to pass (for simplicity, a wave of 40, Divided into 3 waves), it must be red and green lights to dispatch, for the first wave, they see is the green light, allow through, the traffic lights into the road, the light turns red, indicating the back of the 2 waves, to stop to wait for the 1th wave of vehicles all pass, then the traffic lights will turn green, let the 2nd wave through, So running ....
What does this have to do with multi-threaded concurrency? Semaphore is the red and green lights, 3-wave vehicle is 3 concurrent threads, and the main road is multiple threads to concurrent access to common resources, due to limited resources, it must be through semaphore to control the thread access to resources, or become a resource competition, serious words will lead to deadlock and other problems.
The following example shows that if there are n concurrent threads to print the file, but the printer has only 1, a print queue class is first:
Package Yjmyzz.lesson01;import Java.util.concurrent.semaphore;public class PrintQueue { private final Semaphore semaphore; Public PrintQueue () { semaphore = new semaphore (1);//limit shared resources to only 1 (equivalent to only one key) } public void PrintJob ( Object document) { try { semaphore.acquire ();//get access to the shared resource (i.e. get the key)) long Duration = (long) (Math.random () * ten); System.out.printf ("%s:printqueue:printing a Job during%d seconds\n", Thread.CurrentThread (). GetName (), duration); Thread.Sleep (duration); } catch (Interruptedexception e) { e.printstacktrace (); } finally { semaphore.release ();//The key is used up, return it, So that other threads can continue to get the keys in order, access the Resources }} }
Because it is in a multithreaded environment, the real-running job processing has to inherit from runnable (or callable)
Package Yjmyzz.lesson01;public class Job implements Runnable { private PrintQueue PrintQueue; Public Job (PrintQueue PrintQueue) { this.printqueue = PrintQueue; } public void Run () { System.out.printf ("%s:going to print a job\n", Thread.CurrentThread (). GetName ()); Printqueue.printjob (New Object ()); System.out.printf ("%s:the document has been printed\n", Thread.CurrentThread (). GetName ());} }
OK, here's a test:
Package Yjmyzz.lesson01;public class Main {public static void Main (String args[]) { PrintQueue PrintQueue = new P Rintqueue (); int threadcount = 3; Thread thread[] = new Thread[threadcount]; for (int i = 0; i < ThreadCount; i++) { thread[i] = new Thread (new Job (printQueue), "thread" + i); } for (int i = 0; i < ThreadCount; i++) { thread[i].start ();}} }
Output:
Thread0:going to print a job
Thread2:going to print a job
Thread1:going to print a job
Thread0:PrintQueue:Printing a Job during 7 seconds
Thread0:the document has been printed
Thread2:PrintQueue:Printing a Job during 5 seconds
Thread2:the document has been printed
Thread1:PrintQueue:Printing a Job during 0 seconds
Thread1:the document has been printed
From the output, thread 0 prints, thread 2 starts printing, then thread 1, does not appear herd, preemption printer situation. This may not feel much, we put the PrintQueue If we remove the semaphore part, it becomes the following:
Package Yjmyzz.lesson01;public class PrintQueue { //private final Semaphore Semaphore; Public PrintQueue () { //semaphore = new semaphore (1);//limit shared resources to only 1 (equivalent to only one key) } public void PrintJob ( Object document) { try { //semaphore.acquire ();//get access to the shared resource (i.e. get the key)) long Duration = (long) (math.random () *); System.out.printf ("%s:printqueue:printing a Job during%d seconds\n", Thread.CurrentThread (). GetName (), duration); Thread.Sleep (duration); } catch (Interruptedexception e) { e.printstacktrace (); } finally { //semaphore.release ();//The key is run out, you have to return it. So that other threads can continue to get the key, access the Resource }} }
The output of this back:
Thread0:going to print a job
Thread2:going to print a job
Thread1:going to print a job
Thread2:PrintQueue:Printing a Job during 4 seconds
Thread1:PrintQueue:Printing a Job during 8 seconds
Thread0:PrintQueue:Printing a Job during 0 seconds
Thread0:the document has been printed
Thread2:the document has been printed
thread1:the document has been printed
It can be found that 3 threads are all swarmed, and start printing at the same time, regardless of whether the printer is idle, the actual application, this inevitable problem.
OK, go on, suddenly one day, the company has money, and bought 2 printers, so there are 3 printers, how to do? Simply put the printqueue in the constructor
Public PrintQueue () { semaphore = new semaphore (3); }
Is it all right? Think about it, you will find the problem, there is no place in the code to tell the thread which printer is printing, which printer is currently idle, it is still possible to have N threads (n<=3) at the same time grab a printer (ie: if you take control as a key, The equivalent of 3 people each received 1 keys, but the 3 keys are the same, 3 people are looking at the same box, the key to use the hand to grab out of the box.
So we have to improve:
Package Yjmyzz.lesson02;import Java.util.concurrent.semaphore;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class PrintQueue {Private Boolean freeprinters[];//is used to store the state of the printer, True indicates idle, false indicates that the private lock lockprinters;//is being printed to increase the lock, guarantee that multiple threads, can only obtain locks, in order to query which printer idle private final Semaphore Semaphore; Public PrintQueue () {int printernum = 3;//Assume that there are 3 printers semaphore = new semaphore (printernum); Freeprinters = new Boolean[printernum]; for (int i = 0; i < Printernum; i++) {Freeprinters[i] = true;//initialization, all printers are idle by default} lockprinters = new Reentrantlock (); } private int GetPrinter () {int ret =-1; try {lockprinters.lock ();//Lock first, guarantee 1 times only 1 threads to get the idle printer for (int i = 0; i < freeprinters.length; i++ {//traverse the status of all printers, discover that there is a 1th free printer, pick up the number,//and set the printer as busy (because it will be used immediately) if (freeprinte Rs[i]) {ret = i; Freeprinters[i] = false; Break }}} catch (Exception e) {e.printstacktrace (); } finally {///finally don't forget to understand the lock so that the thread behind it can come up with the number Lockprinters.unlock (); } return ret; } public void PrintJob (Object document) {try {semaphore.acquire (); int assignedprinter = GetPrinter ();//Collar long Duration = (long) (Math.random () * 10); System.out.printf ("%s:printqueue:printing a Job in printer%d during%d seconds\n", Thread.CurrentThread (). GetName (), Assignedprinter, duration); Thread.Sleep (duration); Freeprinters[assignedprinter] = true;//after printing, restore the printer to an idle state} catch (Interruptedexception e) {e.printst Acktrace (); } finally {semaphore.release (); } }}
Testing, this time the number of threads increased to 5, the output is similar to the following:
Thread0:going to print a job
Thread4:going to print a job
Thread3:going to print a job
Thread2:going to print a job
Thread1:going to print a job
Thread4:PrintQueue:Printing a Job in Printer1 during 7 seconds
Thread0:PrintQueue:Printing a Job in Printer0 during 4 seconds
Thread3:PrintQueue:Printing a Job in Printer2 during 8 seconds
Thread0:the document has been printed
Thread2:PrintQueue:Printing a Job in Printer0 during 0 seconds
Thread2:the document has been printed
Thread4:the document has been printed
Thread1:PrintQueue:Printing a Job in Printer0 during 0 seconds
Thread3:the document has been printed
Thread1:the document has been printed
As you can see from the output, there can be up to 3 threads using these 3 printers at a time, and the printers used by each thread are not conflicting, and after printing, the idle printer will continue to be used by other threads.
Reference article:
http://ifeve.com/thread-synchronization-utilities-2/
http://ifeve.com/thread-synchronization-utilities-3/
Http://ifeve.com/concurrency-semaphore/
Java Concurrent Programming Learning: Controlling concurrent resources with Semaphore (semaphore)