gpt4 book ai didi

Java 多线程共享列表

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

我需要一些关于 java 多线程的帮助。我有这门课:

public class EdgeServer{

private static final int ServidorBordaID = 9;
private static final String urlLogin = "http://localhost/exehdager-teste/index.php/ci_login/logar";
private static final String insertSensorURI = "http://localhost/exehdager-teste/index.php/cadastros/ci_sensor/gravaSensor";
private static final String insertGatewayURI = "http://localhost/exehdager-teste/index.php/cadastros/ci_gateway/gravaGateway";
private static ArrayList<Gateway> gatewaysCadastrados = new ArrayList<>();

public static void main(String[] args) {
// Start a user thread that runs the UPnP stack
Thread clientThread = new Thread(new Descoberta());
clientThread.setDaemon(false);
clientThread.start();

Thread publicationThread = new Thread(new Publication());
publicationThread.setDaemon(false);
publicationThread.start();
}
}

线程 Descoberta 将根据需要将新的 itens 添加到 gatewaysCadastrados 列表中。并且发布线程将读取此列表并对列表中的每个对象执行一个操作。

我只需要知道如何共享这个变量并将其传递给线程。我需要构建一个信号量来执行此操作吗?

最佳答案

这是示例代码,您可以在两个线程之间共享列表,并且需要使用等待和通知信号量。

public class Descoberta extends Thread {
private final ArrayList<Gateway> a = new ArrayList<>();
public Descoberta( ArrayList<Gateway> a) {
this.a = a;
}

@Override
public void run() {
synchronized (a) {
while(true){ // your condition
a.wait();
}
a.notify();
}
}
}

public class Publication extends Thread {
private final ArrayList<Gateway> b = new ArrayList<>();
public Publication(ArrayList<Gateway> b) {
this.b = b;
}

@Override
public void run() {
synchronized (b) {
while(true){ // your condition
b.wait();
}
b.notify();
}
}
}

public class EdgeServer {
public static void main(String args[]) {
private final ArrayList<Gateway> gatewaysCadastrados = new ArrayList<>();
Thread clientThread = new Descoberta(gatewaysCadastrados);
Thread publicationThread = new Publication(gatewaysCadastrados);
clientThread.start();
publicationThread.start();
}
}

关于Java 多线程共享列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301323/

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