Java concurrent programming: Exchanger

Source: Internet
Author: User

Java concurrent programming: Exchanger

Exchanger
V-object types that can be exchanged

The synchronization point of the thread in which the elements can be paired and exchanged. Each thread presents a method on the entry to the exchange method, matches with the partner thread, and receives the object of its partner when returning the result. Exchanger may be considered as a bidirectional form of SynchronousQueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.

This is an information exchange between two threads.

public class TestExchanger {    public static void main(String[] args)     {        System.out.println(Hello World!);        final Exchanger
  
   > exchanger = new Exchanger
   
    >();        new Thread(){            @Override            public void run(){                List
    
      l = new ArrayList
     
      ();                l.add(1);                l.add(2);                try{                    System.out.println(Thread.currentThread().getName()+:+l);                    l = exchanger.exchange(l);                }catch(InterruptedException ex){                    ex.printStackTrace();                }                System.out.println(Thread.currentThread().getName()+:+l);            }        }.start();        new Thread(){            @Override            public void run(){                List
      
        l = new ArrayList
       
        (); l.add(3); l.add(4); try{ System.out.println(Thread.currentThread().getName()+:+l); Thread.sleep(2000); l = exchanger.exchange(l); }catch(InterruptedException ex){ ex.printStackTrace(); } System.out.println(Thread.currentThread().getName()+:+l); } }.start(); }}
       
      
     
    
   
  

After you add a Thread. sleep (), you will find that the information exchange between the two threads ends before the two threads can be executed downstream simultaneously.

 

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.