在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。