The art of Java concurrent Programming reading notes--the Concurrency tool __ algorithm

Source: Internet
Author: User
Tags object object semaphore static class
Concurrency Tools 1.CountDownLatchAt the same time, threads often use the join method of a thread, where the join method blocks the thread waiting for a join to execute, and in the Join method is continually checking to see if the thread of the join IS alive in the while loop, if it survives, wait (0), The This.notifyall () method is invoked to wake the wait thread until the join thread aborts.          The Countdownlatch class provides similar functionality. The Countdownlatch constructor passes in an integer variable, and then the call to countdownlatch.await blocks the current thread, and every time the countdown method is invoked the variable is reduced by 1, and the thread that is blocked by the await is awakened when it is reduced to 0 o'clock.         In this way, we await in a thread and then pass the Countdownlatch object to another thread, which enables the thread to wait for synergy.  The following is an example of a countdownlatch using a thread to produce 100 object objects into the list collection, which wakes up the thread that was await when the 10 object object was produced. Package study.threadutil;


Import java.util.List;
Import java.util.concurrent.CopyOnWriteArrayList;
Import Java.util.concurrent.CountDownLatch;


public class Countdownlatchtest {
private static list<object> List = new Copyonwritearraylist ();


private static Class Mythread extends Thread {
Private Countdownlatch CDL;


Public Mythread (Countdownlatch c) {
THIS.CDL = C;
}


@Override
public void Run () {
for (int i = 0; i < i++) {
List.add (New Object ());
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Product" + i + "Object");
Cdl.countdown ();
}
}
}


public static void Main (string[] args) {
Countdownlatch CDL = new Countdownlatch (10);
New Mythread (CDL). Start ();
try {
Cdl.await ();
System.out.println ("Get Up");
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

The results of the execution are as follows: Product 0 Object
Product 1 Object
Product 2 Object
Product 3 Object
Product 4 Object
Product 5 Object
Product 6 Object
Product 7 Object
Product 8 Object
Product 9 Object
Get up
Product Object
Product One object
Product Object
Product Object
Product Object
Product Object
Product Object
Product Object
Product Object
Product Object
Product Object
Product Object

2.CyclicBarrierThe role of the synchronization barrier is to block threads at a barrier point until all threads arrive to unify the release, which is equivalent to the kind of team that uses the game and the door opens only when everyone reaches a certain door. The following is a use of cyclibarrier to implement three threads (one is the main thread) to consume 20 digits, each thread consumes 10 digital package study.threadutil;


Import java.util.concurrent.BrokenBarrierException;
Import Java.util.concurrent.CyclicBarrier;


public class Cyclicbarriertest {
private static Cyclicbarrier CB;


private static Class Mythread extends Thread {
@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.println (Thread.CurrentThread () + "" + i);
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
try {
Cb.await ();
catch (Interruptedexception | Brokenbarrierexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread () + "finished");
}
}


public static void Main (string[] args) {
cb = new Cyclicbarrier (3);
New Mythread (). Start ();
New Mythread (). Start ();
try {
Cb.await ();
catch (Interruptedexception | Brokenbarrierexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread () + "finished");
}
}
The results of the implementation are as follows:
Thread[thread-0,5,main]0
Thread[thread-1,5,main]0
Thread[thread-0,5,main]1
Thread[thread-1,5,main]1
Thread[thread-1,5,main]2
Thread[thread-0,5,main]2
Thread[thread-1,5,main]3
Thread[thread-0,5,main]3
Thread[thread-1,5,main]4
Thread[thread-0,5,main]4
Thread[thread-1,5,main]5
Thread[thread-0,5,main]5
Thread[thread-1,5,main]6
Thread[thread-0,5,main]6
Thread[thread-1,5,main]7
Thread[thread-0,5,main]7
Thread[thread-1,5,main]8
Thread[thread-0,5,main]8
Thread[thread-1,5,main]9
Thread[thread-0,5,main]9
Thread[main,5,main] Finished
Thread[thread-1,5,main] Finished
Thread[thread-0,5,main] Finished

Cyclicbarrier implementation of the function and Countdownlatch is similar, but cyclicbarrier can reset the register by resetting the registers can be reused, so cyclicbarrier more applicable scenarios. Cyclicbarrier can also use the Getnumberwaiting method to get the number of threads waiting, and through IsBroken to get blocked threads from being interrupted.
3.SemaphoreLearn from the operating system will not forget the semaphore, in the operating system process resource allocation, often use semaphore semaphore to control the number of resources to obtain the process, to prevent deadlock. The semaphore class has the same function as the signal volume that the operating system has learned, and it provides two ways to control the acquisition and release of resources, acquire and releases. At the same time, Semaphore also provides a intavailablepermits method for returning the number of available resources, Intgetqueuelength method to return the amount of threads waiting to acquire resources. The Booleanhasqueuedthreads method is used to return whether a thread is waiting to acquire a resource, and the Reducepermits method is used to reduce the resource, and the Getqueuedthreads method is used to return all the collection of threads waiting for the resource. But this method is a protected method. , the following is an example of the use of semaphores, in the example, there are three resources, 30 threads, through the semaphore to collaborate with the thread. Package study.threadutil;


Import Java.util.concurrent.Semaphore;


public class Semaphoretest {
private static semaphore SP;


private static Class Mythread extends Thread {
@Override
public void Run () {
try {
Sp.acquire ();
System.out.println (Thread.CurrentThread () + "after acquire resource");
Thread.Sleep (100);
System.out.println (Thread.CurrentThread () + "before release resource");
Sp.release ();
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}


}


public static void Main (string[] args) {
SP = new semaphore (3);
for (int i = 0; i < i++) {
New Mythread (). Start ();
}
}
}

Implementation results are as follows: Thread[thread-0,5,main] after acquire resource
Thread[thread-2,5,main] After acquire resource
Thread[thread-1,5,main] After acquire resource
Thread[thread-1,5,main] before release resource
Thread[thread-0,5,main] before release resource
Thread[thread-2,5,main] before release resource
Thread[thread-4,5,main] After acquire resource
Thread[thread-3,5,main] After acquire resource
Thread[thread-5,5,main] After acquire resource
Thread[thread-4,5,main] before release resource
Thread[thread-5,5,main] before release resource
Thread[thread-3,5,main] before release resource
Thread[thread-7,5,main] After acquire resource
Thread[thread-6,5,main] After acquire resource
Thread[thread-8,5,main] After acquire resource
Thread[thread-7,5,main] before release resource
Thread[thread-6,5,main] before release resource
Thread[thread-8,5,main] before release resource
Thread[thread-9,5,main] After acquire resource
Thread[thread-9,5,main] before release resource


4.ExchangerThe last is a tool class for exchanger thread-swapping data, which provides an exchange method that blocks the current thread and waits for another thread to execute the Exchange method, when two threads have executed the Exchange method. Returns the arguments that were passed in by the other side. The following is an example of a two-thread communication that looks at the number of transmissions over the other package study.threadutil;


Import Java.util.concurrent.Exchanger;


public class Exchangertest {
private static exchanger<long> ex;


private static Class Mythread extends Thread {
@Override
public void Run () {
Long id = thread.currentthread (). GetId ();
System.out.println (Thread.CurrentThread () + ": My ID is" + ID);
try {
Long Youid = Ex.exchange (ID);
System.out.println (Thread.CurrentThread () + ": Your ID is" + youid);
catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}


public static void Main (string[] args) {
ex = new exchanger ();
New Mythread (). Start ();
New Mythread (). Start ();
}
}


The results of the execution are as follows: Thread[thread-1,5,main]: my ID IS13
Thread[thread-0,5,main]: my ID is12
Thread[thread-0,5,main]: Your ID is 13
Thread[thread-1,5,main]: Your ID is 12
Related Article

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.