Ele é usado para alcançar a troca de dados entre duas pessoas. trocar os dados um com o outro essência
Copie o código do código da seguinte forma:
pacote com.ljq.test.thread;
Importar java.util.concurrent.exchanger;
Importar java.util.concurrent.executorService;
Importar java.util.concurrent.executores;
classe pública trocangrtest {
Public static void main (string [] args) {{
ExecutorService Service = executores.newcachedthreadpool ();
Final Exchange Exchange = new Exchange ();
Service.execute (new Runnable () {)
public void run () {
tentar {
String data1 = "Zhang San";
System.out.println ("thread" + thread.currentThread (). GetName () + "agora está transformando os dados '" + data1 + "' out");
Thread.sleep ((longo) (math.random ()*10000));
String data2 = (string) trocador.exchange (data1);
System.out.println ("thread" + thread.currentThread (). GetName () + "dados substituídos é '" + data2 + "'");
} Catch (Exceção e) {{
}
}
});
Service.execute (new Runnable () {)
public void run () {
tentar {
String data1 = "li si";
System.out.println ("thread" + thread.currentThread (). GetName () + "agora está transformando os dados '" + data1 + "' out");
Thread.sleep ((longo) (math.random ()*10000));
String data2 = (string) trocador.exchange (data1);
System.out.println ("thread" + thread.currentThread (). GetName () + "dados substituídos é '" + data2 + "'");
} Catch (Exceção e) {{
}
}
});
}
}
Resultados das costas:
Copie o código do código da seguinte forma:
O thread pool-thread-1 está substituindo os dados 'Zhang San' fora do thread pool-1-thread-2 está alterando os dados para o thread pool-thread-1 '
Os dados do thread pool-1-thread-2 são substituídos por 'Zhang San'