java多執行緒-Thread兩個執行緒交換資料Exchanger
/**
* 2017-4-21
* author:饒為
* Administrator
*/
package Thread;
import java.util.concurrent.Exchanger;
/**
* 2017-4-21
* author:饒為
* Administrator
*/
public class ExchangerTest {
public static void main(String[] args) {
final Exchanger<String> exchanger = new Exchanger<String>();
new Thread(){
public void run(){
String a = "第一個執行緒";
try {
a = exchanger.exchange(a);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1"+a);
}
}.start();
new Thread(){
public void run(){
String a = "第二個執行緒";
try {
a = exchanger.exchange(a);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread2"+a);
}
}.start();
new Thread(){
public void run(){
String a = "第三個執行緒";
try {
a = exchanger.exchange(a);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread3"+a);
}
}.start();
new Thread(){
public void run(){
String a = "第四個執行緒";
try {
a = exchanger.exchange(a);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread4"+a);
}
}.start();
}
}