在Java中,可以通過調用Exchanger類的close()方法來優雅地關閉Exchanger。在調用close()方法之前,可以先調用exchanger的exchange()方法來確保所有線程都已完成交換操作。然后再調用close()方法來關閉Exchanger。以下是一個示例代碼:
Exchanger<Integer> exchanger = new Exchanger<>();
// 創建線程進行交換操作
Thread t1 = new Thread(() -> {
try {
int result = exchanger.exchange(1);
System.out.println("Thread 1 exchanged: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
int result = exchanger.exchange(2);
System.out.println("Thread 2 exchanged: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
// 確保所有線程都已完成交換操作
exchanger.exchange(null);
// 關閉Exchanger
exchanger.close();
通過以上代碼,我們可以確保所有線程都已完成交換操作后再關閉Exchanger,從而實現優雅地關閉Exchanger。