Java thread communication and thread concurrency Library

Source: Internet
Author: User

-------
Android training and Java training. We look forward to communicating with you! ----------

Java 5 thread lock technology

Lock & condition for Synchronous thread Communication
Lock is more object-oriented than the traditional synchronized method. The code blocks executed by two threads must be synchronized and mutually exclusive.
Readwritelock: Multiple read locks are not mutually exclusive. Read locks and write locks are mutually exclusive. If multiple threads are required to read data at the same time but cannot write data at the same time, add a read lock. If the code modifies data and adds a write lock to the Code, the write lock is exclusively occupied by the thread.
When waiting for condition, "false Wakeup" is allowed. condition should always be waited in a loop and the status being waited should be tested.
Condition condition = lock. newcondition ();
Use the read/write lock cache Function

Class cacheddata {object data; volatile Boolean cachevalid; reentrantreadwritelock RWL = new reentrantreadwritelock (); void processcacheddata () {RWL. readlock (). Lock (); If (! Cachevalid) {// If the cache does not contain data // you must release the read lock RWL before using the write lock. readlock (). unlock (); RWL. writelock (). lock (); // check if (! Cachevalid) {DATA =... // write data cachevalid = true;} // after the data is written, read the lock and release the write lock RWL. readlock (). lock (); RWL. writelock (). unlock ();} Use (data); RWL. readlock (). unlock ();}}
Semaphore count signal lamp

Restrict the number of threads that can access certain resources. The number of threads that can enter the same code segment.
Number of concurrent threads allowed by semaphore (INT permits) permits.
Acquire () obtains a license from this semaphore.
Void release () releases a license.

The semaphore object of a single semaphore can implement the mutex lock function, and the lock can be obtained by one thread, and then released by another thread ".

Public class semaphoretest {public static void main (string [] ARGs) {executorservice service = executors. newcachedthreadpool (); Final semaphore sp = new semaphore (3); // create a signal lamp for (INT I = 0; I <10; I ++) {runnable = new runnable () {public void run () {try {sp. acquire ();} catch (interruptedexception E1) {e1.printstacktrace ();} system. out. println ("Thread" + thread. currentthread (). getname () + "Incoming, current" + (3-sp.availablepermits () + "concurrent"); try {thread. sleep (long) (math. random () * 10000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("Thread" + thread. currentthread (). getname () + "coming soon"); SP. release (); // the following code is sometimes inaccurate because it is not integrated with the above Code into the atomic unit system. out. println ("Thread" + thread. currentthread (). getname () + "Left, current" + (3-sp.availablepermits () + "concurrent" concurrent threads cannot exceed service.exe cute (runnable); // submit the task to the thread pool }}}
Cyclicbarrier

A synchronization helper class that allows a group of threads to wait for each other until it reaches a public barrier point.

Public class javasicbarriertest {public static void main (string [] ARGs) {executorservice service = executors. newcachedthreadpool (); // create a thread pool final javasicbarrier cb = new javasicbarrier (3); // create a circular barrier with a thread count of 3for (INT I = 0; I <3; I ++) {// create three threads and hand them to the thread pool to execute runnable = new runnable () {public void run () {try {thread. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "Will arrive at collection location 1, current" + (CB. getnumberwaiting () + 1) + "has arrived," + (CB. getnumberwaiting () = 2? "It's all done, continue": "Waiting"); CB. await (); // wait for other thread threads. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "coming to collection Location 2, current" + (CB. getnumberwaiting () + 1) + "arrived," + (CB. getnumberwaiting () = 2? "It's all done, continue": "Waiting"); CB. await (); thread. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "coming to collection location 3, current" + (CB. getnumberwaiting () + 1) + "arrived," + (CB. getnumberwaiting () = 2? "It's all done, continue": "Waiting"); CB. await ();} catch (exception e) e.printstacktrace({{}}{service.exe cute (runnable);} service. shutdown ();}}
Countdownlatch

Countdownlatch (INT count) constructs a countdownlatch initialized with a given count.
Call the countdown method to reduce the counter by 1. When the Count reaches 0, all the waiting persons or individual waiting persons start to execute.

Public class countdownlatchtest {public static void main (string [] ARGs) {executorservice service = executors. newcachedthreadpool (); Final countdownlatch cdorder = new countdownlatch (1); final countdownlatch cdanswer = new countdownlatch (3); For (INT I = 0; I <3; I ++) {runnable = new runnable () {// create three threads public void run () {try {system. out. println ("Thread" + thread. currentthread (). getname () + "preparing to accept command"); cdorder. await (); // wait for the main thread to control the cdorder to start the task system. out. println ("Thread" + thread. currentthread (). getname () + "commands accepted"); thread. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "response command processing result"); cdanswer. countdown (); // notification of task completion to the main thread} catch (exception e) e.printstacktrace({%}%%%%service.exe cute (runnable);} Try {thread. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "coming soon"); cdorder. countdown (); // return count to 0 and start executing the task system. out. println ("Thread" + thread. currentthread (). getname () + "sent command, waiting for result"); cdanswer. await (); // wait until the sub-thread completes system. out. println ("Thread" + thread. currentthread (). getname () + "all response results received");} catch (exception e) {e. printstacktrace ();} service. shutdown ();}}
Exchanger

Implements data exchange between two threads holding the same exchanger object.
The V Exchange (v x) method exchanges data.
 

Blocked queue

Public class arrayblockingqueue <E> extends abstractqueue <E> implements blockingqueue <E>, serializable
Sort the elements in FIFO order.
The producer uses the PUT Method to put data, and the consumer uses the take method to retrieve data.
Insert the new element to the end of the queue. The queue acquisition operation obtains the element starting from the queue header.
Size () returns the number of elements in this queue.
The thread communication function can be implemented by two synchronization queue objects with only one element.

Questions about Skynet:

The code in the test class is constantly generating data and then handing it to the testdo. dosome () method for processing, as if the producer is continuously generating data and the consumer is continuously consuming data.
The program has 10 threads to consume the data generated by the producer. These consumers call testdo. the dosome () method is used for processing. Therefore, each consumer needs to finish processing in one second. The program should ensure that these consumer threads consume data in sequence. Only after the previous consumer consumes data, data can be consumed by the next consumer, but the data obtained by these consumer threads must be ordered.

Public class test {public static void main (string [] ARGs) {final semaphore = new semaphore (1); final synchronousqueue <string> queue = new synchronousqueue <string> (); for (INT I = 0; I <10; I ++) {New thread (New runnable () {@ overridepublic void run () {try {semaphore. acquire (); string input = queue. take (); // ensure that the data is retrieved in order string output = testdo. dosome (input); system. out. println (thread. currentthread (). getname () + ":" + output); semaphore. release ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start ();} system. out. println ("begin:" + (system. currenttimemillis ()/1000); For (INT I = 0; I <10; I ++) {// This line cannot be changed to string input = I + ""; // This line cannot be changed. Try {queue. put (input); // generate data cyclically in the main thread and put the data into the synchronization queue. The subthread operates on the queue} catch (interruptedexception e) {e. printstacktrace () ;}}}// this testdo class testdo {public static string dosome (string input) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} string output = input + ":" + (system. currenttimemillis ()/1000); Return output ;}}
Synchronization set

Collection in the traditional mode cannot be modified when the collection is iterated.
Synchronization collection class: concurrenthashmap, concurrentskiplistmap, concurrentskiplistset, copyonwritearraylist, and copyonwritearrayset. When many threads are expected to access a given collection, concurrenthashmap is generally better than the synchronized hashmap, and concurrentskiplistmap is generally better than the synchronized treemap. When the expected reading and traversal are much larger than the number of list updates, the copyonwritearraylist is better than the synchronized
Arraylist.

Air Network interview questions:

If several threads call testdo. when the dosome (Key, value) method is passed in, the key is equal (equals is compared to true), then these threads should mutually exclusive queue output results, that is, when the keys of two threads are "1", one of them outputs results 1 second later than the other threads, as shown below:
4: 4: 1258199615
1: 1: 1258199615
3:3: 1258199615
1: 2: 1258199616

Import Java. util. iterator; import Java. util. concurrent. copyonwritearraylist; // The test class public class test extends thread {private testdo; private string key; private string value; public test (string key, string key2, string value) cannot be modified) {This. testdo = testdo. getinstance ();/* constant "1" and "1" are the same object. The following code uses the "1" + "method to generate a new object, the implementation content is not changed, and it is still equal (both are "1"), but the object is no longer the same effect */This. key = Key + key2; this. value = value;} public stati C void main (string [] ARGs) throws interruptedexception {Test A = new test ("1", "", "1"); Test B = new test ("1 ", "", "2"); Test C = new test ("3", "", "3"); test D = new test ("4 ","", "4"); system. out. println ("begin:" + (system. currenttimemillis ()/1000);. start (); B. start (); C. start (); D. start ();} public void run () {testdo. dosome (Key, value) ;}} class testdo {private testdo () {} Private Static testdo _ instance = new test Do (); public static testdo getinstance () {return _ instance;} // when executing dosome, You need to judge and add the key, private copyonwritearraylist keys = new copyonwritearraylist (); Public void dosome (Object key, string value) {object o = key; // synchronize mutex lock objects with keys if (! Keys. contains (O) {keys. add (o);} else {for (iterator iter = keys. iterator (); ITER. hasnext ();) {try {thread. sleep (20); // test the code so that you can execute the set operation for a while.} catch (interruptedexception e) {e. printstacktrace ();} object oo = ITER. next (); If (oo. equals (O) {o = Oo; break ;}} synchronized (o) // the code to be partially synchronized in braces cannot be modified! {Try {thread. sleep (1, 1000); system. out. println (Key + ":" + value + ":" + (system. currenttimemillis ()/1000);} catch (interruptedexception e) {e. printstacktrace ();}}}}

-------
Android training and Java training. We look forward to communicating with you! ----------

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.