juc--Thread Synchronization Accessibility tool Class (Exchanger,completablefuture)

Source: Internet
Author: User

Exchanger Swap Space

If there are two threads, one thread is responsible for producing the data, and the other thread is responsible for consuming the data, there must be a common area between the two threads, and the implementation of this area is called Exchangerin the Juc package.

The Java.util.concurrent.Exchanger class represents a convergence point where two threads can exchange objects with each other.

The methods defined in the Exchanger class are as follows:

    • Construction Method:
      PUBILC Exchanger ();  Create an Object
    • Set up and get:
      Public V Exchange (v x) throws Interruptedexception

Example: using Exchanger for interchange processing

 Packageso.strong.mall.concurrent;ImportJava.util.concurrent.Exchanger;ImportJava.util.concurrent.TimeUnit; Public classExchanerdemo { Public Static voidMain (string[] args) {FinalExchanger<string> Exchanger =NewExchanger<> ();//prepare a swap space         for(inti = 0; I < 3; i++) {//3 Consumers            NewThread (NewRunnable () {@Override Public voidrun () { while(true) {                        Try{String Data= Exchanger.exchange (NULL); TimeUnit.SECONDS.sleep (2); if(Data! =NULL) {System.out.println ("[" + Thread.CurrentThread (). GetName () + "] Get data:" +data); }                        } Catch(Exception e) {e.printstacktrace (); }                    }                }            }, "Consumer-" +i). Start (); }         for(inti = 0; I < 2; i++) {//2 Producers            Final inttemp =i; NewThread (NewRunnable () {@Override Public voidrun () { for(intj = 0; J < 2; J + +) {String data= "itermis-" + temp + "-" +J; Try{TimeUnit.SECONDS.sleep (2);//slowing the pace of producersexchanger.exchange (data); System.out.println ("[" + Thread.CurrentThread (). GetName () + "] produced data:" +data); } Catch(Exception e) {e.printstacktrace (); }                    }                }            }, "Producer-" +i). Start (); }    }}
[Producer-1] produced data: itermis-1-0[producer-1] produced data: itermis-1-1[consumer-1] acquired data: itermis-1-0[Producer-0] produced data: itermis-0-0[producer-0] Produced data: itermis-0-1[consumer-2] get data: itermis-0-1

  

completablefuture Thread Callbacks

Now imagine a scenario, for example: bombing a target with artillery

All execution threads go into a blocking state before they receive the command, and the next action is processed until the specific command is received.

Java.util.concurrent.CompletableFuture is a class added in Java8 that provides a new way to complete asynchronous processing, including the non-blocking way of compositing and combining events.

The following methods are available in the Completablefuture class:

    • Construction Method:
      public Completablefuture ();
    • Get command:
      Public T get () throws Interruptedexception,executionexception

Example: Using Completablefuture for artillery bombing operations

 Packagecom.itermis.concurrent;Importjava.util.concurrent.CompletableFuture;ImportJava.util.concurrent.TimeUnit;

Public classCompletablefuturedemo { Public Static voidMain (string[] args)throwsException {completablefuture<String> future =NewCompletablefuture<>(); for(inti = 0; I < 4; i++) { NewThread ((){System.out.println ("before[" + thread.currentthread (). GetName () + "] into the artillery position, waiting for orders, ready to fire. "); Try{String cmd= Future.get ();//receive Command if("Fire". Equals (cmd)) {System.out.println ("after[" + thread.currentthread (). GetName () + "] receive the command, fire immediately, dry the dead fat Man. "); } if("Cancel". Equals (cmd)) {System.out.println ("after[" + thread.currentthread (). GetName () + "] receive the retreat order and go home to sleep. "); } } Catch(Exception e) {e.printstacktrace (); } }, "Artillery-" +i). Start (); } TimeUnit.SECONDS.sleep (3);//wait 3 secondsFuture.complete ("Cancel");//gives the execution command }}
before[Artillery-1] into the artillery position, waiting for orders, ready to fire. Before[Artillery-0] into the artillery position, waiting for orders, ready to fire. before[Artillery-2] into the artillery position, waiting for orders, ready to fire. before[Artillery-3] into the artillery position, waiting for orders, ready to fire. Sleep 3 seconds after[Artillery-1] received a retreat order to go home to sleep. After[Artillery-0] received the retreat order and went home to sleep. after[Artillery-2] received the retreat order and went home to sleep. after[Artillery-3] received the retreat order and went home to sleep.

The processing of this class is primarily based on the implementation of the future threading model.

For this class, asynchronous thread execution can be handled in addition to the above usage. You can also use one of the static methods provided in this class when creating a Completablefuture class object:

public static completablefuture<void> RunAsync (Runnable Runnable)

Example: Replace the implementation method to achieve the above bombing operation:

 Packagecom.itermis.concurrent;Importjava.util.concurrent.CompletableFuture;ImportJava.util.concurrent.TimeUnit; Public classCompletablefuturedemoii { Public Static voidMain (string[] args) {completablefuture<Void> future = Completablefuture.runasync ((){System.out.println ("[Future] general is in the gentle village dream, waiting for the general to wake up cannon."); Try{TimeUnit.SECONDS.sleep (3); } Catch(Exception e) {e.printstacktrace (); } System.out.println ("[Future] the general woke up and began to work.");        });  for(inti = 0; I < 4; i++) {            NewThread ((){System.out.println ("before[" + thread.currentthread (). GetName () + "] into the artillery position, waiting for orders, ready to fire. "); Try{System.out.println ("after[" + thread.currentthread (). GetName () + "] receive the command, fire immediately, dry the dead fat Man. " +future.get ()); } Catch(Exception e) {e.printstacktrace (); }            }, "Artillery-" +i). Start (); }    }}
The general is dreaming of a tender village, waiting for the general to wake up and fire the cannon. before[Artillery-1] into the artillery position, waiting for orders, ready to fire. Before[Artillery-0] into the artillery position, waiting for orders, ready to fire. before[Artillery-2] into the artillery position, waiting for orders, ready to fire. before[Artillery-3] into the artillery position, waiting for orders, ready to fire. Sleep 3 seconds [future] the general woke up and began to work. after[Artillery-2] receive orders, fire immediately, dry the dead fat Man. Nullafter[Artillery-0] receive orders, fire immediately, dry the dead fat Man. nullafter[Artillery-3] receive orders, fire immediately, dry the dead fat Man. nullafter[Artillery-1] receive orders, fire immediately, dry the dead fat Man. Null

The biggest benefit of this class of completablefuture is that it provides the execution trigger point for all waiting threads.

juc--Thread Synchronization Accessibility tool Class (Exchanger,completablefuture)

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.