これは、2人の人との間のデータ交換を実現するために使用されます。お互いのエッセンスとデータを交換します
次のようにコードコードをコピーします。
パッケージcom.ljq.test.thread;
java.util.concurrent.exchangerをインポートします。
java.util.concurrent.executorserviceをインポートします。
java.util.concurrent.executorsをインポートします。
パブリッククラスの交換{
public static void main(string [] args){{
executorservice service = executors.newcachedthreadpool();
最終Exchange Exchange = new Exchange();
service.execute(new runnable(){)
public void run(){
試す {
文字列data1 = "Zhang San";
system.out.println( "swree" + thread.currentthread()。getName() + "はデータをめくる '" + data1 + "' out");
thread.sleep((long)(math.random()*10000));
文字列data2 =(string)endganger.exchange(data1);
system.out.println( "swree" + thread.currentthread()。getName() + "置換データは '" + data2 + "'");
} catch(例外e){{
}
}
});
service.execute(new runnable(){)
public void run(){
試す {
文字列data1 = "li si";
system.out.println( "swree" + thread.currentthread()。getName() + "はデータをめくる '" + data1 + "' out");
thread.sleep((long)(math.random()*10000));
文字列data2 =(string)endganger.exchange(data1);
system.out.println( "swree" + thread.currentthread()。getName() + "置換データは '" + data2 + "'");
} catch(例外e){{
}
}
});
}
}
バック結果:
次のようにコードコードをコピーします。
スレッドプール-thread-1は、スレッドからデータ「Zhang San」をスレッドPool-1-Thread-2から置き換えています。
スレッドPool-1-Thread-2のデータは「Zhang San」に置き換えられます