Package Org.rui.thread.newc;import Java.util.list;import Java.util.concurrent.copyonwritearraylist;import Java.util.concurrent.exchanger;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors ; Import Java.util.concurrent.timeunit;import Org.rui.generics.anonymity.basicgenerator;import Org.rui.generics.anonymity.generator;import org.rui.thread.newc.semaphore.fat;/** * @author Lenovo * Switch fences between two tasks, When these fences enter the task, they and themselves have an object, and when they leave, they all have objects previously held by the object. * * = * can have more objects being created while being consumed. * *//** * producer */class exchangerproduer<t> implements Runnable{private generator<t> generator;//Generator Private Ex Changer<list<t>> exchanger;private list<t> holder;//Object collection Exchangerproduer (Exchanger<List<T >> Exchg, generator<t> generator,list<t> holder) {this.generator = Generator;this.exchanger = Exchg; This.holder = holder;} @Overridepublic void Run () {Try{while (! Thread.interrupted ()) {for (int i = 0; i < exchangerdemo.size; i++) {//Put the processed object into the collectionT t = Generator.next (); System.err.println (Thread.CurrentThread (). GetName () + ">> Production object:" + t); Holder.add (Generator.next ());/** * Exchange (V) * waits for another thread to reach this interchange point (unless the current thread is interrupted), then routes the given object to that thread and receives the object for that thread. *///Exchange Full for empty: all Empty holder = Exchanger.exchange (holder);}}} catch (Interruptedexception e) {//OK to terminate the this way can be terminated in this manner}}}/** * Demo main * @author Lenovo * * @param <T&G T */class exchangerconsumer<t> implements Runnable{private exchanger<list<t>> exchanger;private List <T> holder;private volatile T value; Exchangerconsumer (exchanger<list<t>> ex, list<t> holder) {Exchanger = Ex;this.holder = holder;} @Overridepublic void Run () {Try{while (! Thread.interrupted ()) {//The consumer takes out the object for processing exchanger.exchange (holder); for (T x:holder) {value = x;//fetch out valuesystem.out . println (Thread.CurrentThread (). GetName () + "consumption object:" + x); Holder.remove (x);//OK for copyomwritearraylist consumption complete Removal}} catch (Interruptedexception e) {//OK to terminate this}system.out.println ("Final value:" + value);}} public class exchangerdemo{static int size = 10;static int delay = 5;public static void Main (string[] args) throws Excepti on{string[] Argss = new string[]{"Ten", "5"};if (Argss.length > 0) {size = new Integer (Argss[0]);} if (Argss.length > 1) {delay = new Integer (Argss[0]);} Executorservice exec = Executors.newcachedthreadpool (); Exchanger<list<fat>> XC = new exchanger<list<fat>> ();//----------------------producer// A thread-safe variant of the Copyonwritearraylist >>>arraylist,//Where all mutable operations (add, set, and so on) are implemented by a new copy of the underlying array list<fat> Producerlist = new copyonwritearraylist<fat> (); Exchangerproduer Produer = new Exchangerproduer<fat> (Xc,basicgenerator.create (Fat.class), producerList);//When calling Exchange (), which blocks until the other task calls its own Exchange () method, at which point the two Exchange () methods will all be completed, and list<t> will be transferred to each other: Exec.execute (Produer); TimeUnit.SECONDS.sleep (delay),//----------------------consumption list<fat> consumerlist = new Copyonwritearraylist <fat> ();//Consumer Exec.execute (New exchangerconsumer<fat> (XC, consumerlist)); TimeUnit.SECONDS.sleep (delay);//try to stop all the active tasks that are being performed, suspend processing of the awaited task, and return to the list of tasks awaiting execution. Exec.shutdownnow ();}} /** * Output: * Final value:fat>>id:89024 */
Related helper Classes
Generator.javapackage Org.rui.generics.anonymity;public interface Generator<t> {//returns the inner object of the generic type T next ();
-----------
Package Org.rui.generics.anonymity;public class Basicgenerator<t> implements Generator<t>{private class <T> type;public basicgenerator (class<t> type) {this.type = type;} @Overridepublic T Next () {Try{return type.newinstance ();} catch (Exception e) {throw new RuntimeException (e);}} public static <T> generator<t> Create (class<t> type) {return new basicgenerator<t> (type);}
Package Org.rui.thread.newc.semaphore;public class fat{private volatile double d;private static int counter = 0;private fi nal int id = counter++;p ublic Fat () {//expensive, interruptible operation:for (int i = 1; i < 10000; i++) {D + = (Math.PI + MATH.E)/(double) I;}} public void operation () {System.out.println ("operation>> " +this); @Overridepublic String toString () {return ' Fat>>id: ' + ID;}}
Java multithreading concurrency--exchanger two tasks Exchange objects