在Java中,Exchanger類可以用來解決數據交換的問題。Exchanger類提供了一種簡單的機制,可以讓兩個線程在同一個點上交換數據。
要使用Exchanger類進行數據交換,首先需要創建一個Exchanger對象,然后兩個線程可以調用exchanger()方法來交換數據。其中一個線程將要交換的數據傳遞給exchanger()方法,而另一個線程則從exchanger()方法中獲取另一個線程傳遞的數據。
以下是一個簡單的示例,演示了如何使用Exchanger類進行數據交換:
import java.util.concurrent.Exchanger;
public class DataExchangeExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
Thread thread1 = new Thread(() -> {
try {
String data1 = "Data from Thread 1";
System.out.println("Thread 1 is exchanging data: " + data1);
String data2 = exchanger.exchange(data1);
System.out.println("Thread 1 received data: " + data2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
String data1 = "Data from Thread 2";
System.out.println("Thread 2 is exchanging data: " + data1);
String data2 = exchanger.exchange(data1);
System.out.println("Thread 2 received data: " + data2);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
}
}
在上面的示例中,兩個線程分別交換了數據,并將其打印出來。可以看到,Exchanger類提供了一種方便的方式來在兩個線程之間進行數據交換。