gpt4 book ai didi

Java : threaded serial port read with Java. util.concurrent 线程访问

转载 作者:行者123 更新时间:2023-11-30 07:36:42 25 4
gpt4 key购买 nike

我正在尝试编写一个 Java 串行设备驱动程序并想使用(对我来说是新的)java.util.concurrent 包。我有一种发送数据包然后等待 ACK 的方法。我打算有炭。接待在不同的线程中运行。如果接收线程获得 ACK,它应该使用发送数据包函数通知线程。接收线程实现了一个状态机,并应通知所有监听器已解码数据包。

我想我知道如何使用直接线程、waitnotify 等来做到这一点,但我不确定如何使用新的并发包来做到这一点。非常感谢任何指点。

最佳答案

使用 CyclicBarrier .这是其 Javadoc 中的相关引用:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

因此,您需要为多个2 方创建一个CyclicBarrier 并让接收方线程在ACK 和之后调用await()让发送方线程在执行 SEND 之前调用 await()

这是一个 SSCCE让你开始。

package com.stackoverflow.q3379797;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(2);
Receiver receiver = new Receiver(barrier);
Sender sender = new Sender(barrier);

ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(receiver);
executor.submit(sender);
}

}

class Receiver implements Runnable {

private CyclicBarrier barrier;

public Receiver(CyclicBarrier barrier) {
this.barrier = barrier;
}

@Override
public void run() {
while (true) {
try {
// Wait for ACK (the sleep just simulates that).
Thread.sleep(2000);
System.out.println("ACK");

// Then notify.
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

class Sender implements Runnable {

private CyclicBarrier barrier;

public Sender(CyclicBarrier barrier) {
this.barrier = barrier;
}

@Override
public void run() {
while (true) {
try {
// Wait for notify.
barrier.await();

// Now do SEND.
System.out.println("SEND");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

您将在标准输出中看到以下内容:

(2 seconds)ACKSEND(2 seconds)ACKSEND(2 seconds)ACKSEND

关于Java : threaded serial port read with Java. util.concurrent 线程访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3379797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com