Java開発Exchangerを使ってスレッドサンプルコード

参考コード:
package com.jz345.javacource;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExcehangeFun {

public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable(){
public void run() {
try{
String data1 = “testdata11";
System.out.println(“Thread:\n" + Thread.currentThread().getName() +"test data" + data1 +"change");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String) exchanger.exchange(data1);
System.out.println(“Thread:\n" + Thread.currentThread().getName() +
“return data" + data2);
}catch(Exception e){

}
}
});

service.execute(new Runnable(){
public void run() {
try{
String data1 = “testdata22";
System.out.println(“Thread:\n" + Thread.currentThread().getName() + “change data" + data1 +"save");
Thread.sleep((long)(Math.random()*10000));
String data2 = (String)exchanger.exchange(data1);
System.out.println(“Thread:\n" + Thread.currentThread().getName() + “return data" + data2);
}catch(Exception e){

}
}
});
}
}

実行結果:

Thread:
pool-1-thread-1test datatestdata11change
Thread:
pool-1-thread-2change datatestdata22save
Thread:
pool-1-thread-1return datatestdata22
Thread:
pool-1-thread-2return datatestdata11

Java

Posted by arkgame