Java中的Exchanger類可以與線程池配合使用,以實現線程之間的數據交換。Exchanger類允許兩個線程在指定的同步點交換數據。這對于需要線程之間協調和同步的場景非常有用,比如生產者-消費者模型。
以下是一個示例代碼,演示了如何在線程池中使用Exchanger類進行數據交換:
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangerExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(() -> {
try {
String data1 = "Data from Thread 1";
System.out.println("Thread 1 has data: " + data1);
String exchangedData = exchanger.exchange(data1);
System.out.println("Thread 1 received: " + exchangedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executor.execute(() -> {
try {
String data2 = "Data from Thread 2";
System.out.println("Thread 2 has data: " + data2);
String exchangedData = exchanger.exchange(data2);
System.out.println("Thread 2 received: " + exchangedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executor.shutdown();
}
}
在這個示例中,我們創建了一個包含兩個線程的線程池,并使用Exchanger類在兩個線程之間交換數據。線程1創建了一個字符串數據并交換給線程2,而線程2創建了另一個字符串數據并交換給線程1,最終兩個線程分別打印出接收到的對方交換的數據。
通過這種方式,我們可以在線程池中實現線程之間的數據交換,實現更加靈活和高效的線程協作。