三进多线程,线程数据交换,Exchanger就够了

it2022-12-27  96

Exchanger简介

如果对java并包(java.util.concurrent)知道的话,那么可能知道CountDownLatch、CyclicBarrier这些多线程并发工具,不熟悉的话可以看以下文章。

Exchanger也在其中,顾名思义,Exchanger是用于两个线程交换数据的,最重要的是exchange()方法,这是一个阻塞方法,意味着线程将调用exchange()方法时在交换点等待,直到另一个线程到达,一旦另一个线程到达,两个线程将会交换各自的数据并返回。还有个重载方法接收TimeUnit对象,能使得等待到一定时间后返回。

exchange()方法在等待过程中可以中断他,就会抛出InterruptedException异常。

示例

我们给每个线程起个名字,分别为thread-a、thread-b,线程中各自调用exchange()方法,传入自己处理好的数据,当最后打印的时候,会看到是打印的其他线程的数据。

package com.socket; import java.io.IOException; import java.util.concurrent.Exchanger; public class Main { public static void main(String[] args) throws IOException { Exchanger<String> stringExchanger = new Exchanger<>(); new Thread(() -> { try { System.out.println(Thread.currentThread().getName()+":"+stringExchanger.exchange("a")); } catch (InterruptedException e) { e.printStackTrace(); } },"thread-a").start(); new Thread(() -> { try { System.out.println(Thread.currentThread().getName()+":"+stringExchanger.exchange("b")); } catch (InterruptedException e) { e.printStackTrace(); } },"thread-b").start(); } } thread-b:a thread-a:b

如果指定了超时的话,会抛出TimeoutException异常。

public class Main { public static void main(String[] args) throws IOException { Exchanger<String> stringExchanger = new Exchanger<>(); new Thread(() -> { try { System.out.println(Thread.currentThread().getName()+":"+stringExchanger.exchange("a",1, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } },"thread-a").start(); // new Thread(() -> { // try { // System.out.println(Thread.currentThread().getName()+":"+stringExchanger.exchange("b")); // } catch (InterruptedException e) { // e.printStackTrace(); // } // },"thread-b").start(); } } java.util.concurrent.TimeoutException at java.util.concurrent.Exchanger.exchange(Exchanger.java:626) at com.socket.Main.lambda$main$0(Main.java:14) at java.lang.Thread.run(Thread.java:748)

在看看中断他。

package com.socket; import java.io.IOException; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Main { public static void main(String[] args) throws IOException { Exchanger<String> stringExchanger = new Exchanger<>(); Thread thread = new Thread(() -> { try { System.out.println(Thread.currentThread().getName() + ":" + stringExchanger.exchange("a", 3, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } }, "thread-a"); thread.start(); thread.interrupt(); // new Thread(() -> { // try { // System.out.println(Thread.currentThread().getName()+":"+stringExchanger.exchange("b")); // } catch (InterruptedException e) { // e.printStackTrace(); // } // },"thread-b").start(); } } java.lang.InterruptedException at java.util.concurrent.Exchanger.exchange(Exchanger.java:624) at com.socket.Main.lambda$main$0(Main.java:14) at java.lang.Thread.run(Thread.java:748)
最新回复(0)