同時ツールクラス:Exchange
2265 ワード
Exchange
一、作用
二、コード
package com.intellif.mozping.concurrentutil.exchangep;
import com.intellif.mozping.tools.SleepTools;
import java.util.ArrayList;
import java.util.concurrent.Exchanger;
/**
* @author by mozping
* @Classname ExchangeTest
* @Description Exchange
* @Date 2019/1/2 18:50
*/
public class ExchangeTest {
private static final Exchanger> exchange = new Exchanger<>();
public static void main(final String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
ArrayList arr1 = new ArrayList<>();
ArrayList arr11 = new ArrayList<>();
arr1.add(1);
arr1.add(2);
arr1.add(3);
try {
arr11 = exchange.exchange(arr1);
} catch (InterruptedException e) {
e.printStackTrace();
}
SleepTools.randomSecond(5);
System.out.println("Thread1 :"+arr1.toString());
System.out.println("Thread1 :"+arr11.toString());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
ArrayList arr2 = new ArrayList<>();
ArrayList arr22 = new ArrayList<>();
arr2.add(11);
arr2.add(22);
arr2.add(33);
try {
arr22 = exchange.exchange(arr2);
} catch (InterruptedException e) {
e.printStackTrace();
}
SleepTools.randomSecond(5);
System.out.println("Thread2 :" + arr2.toString());
System.out.println("Thread2 :" + arr22.toString());
}
}).start();
}
}
:
Thread1 :[1, 2, 3]
Thread1 :[11, 22, 33]
Thread2 :[11, 22, 33]
Thread2 :[1, 2, 3]