gpt4 book ai didi

java - 如何从两个单独的线程更新数组

转载 作者:行者123 更新时间:2023-12-02 03:25:48 27 4
gpt4 key购买 nike

我正在运行两个单独的线程:

List<String> where = new ArrayList<String>();
public static void main(String[] args) {
MainWatch R1 = new MainWatch("C:\\test", "Thread1");
R1.start();
MainWatch R2 = new MainWatch("C:\\test2", "thread2");
R2.start();
}

我希望他们都更新 where 数组:

public class MainWatch implements Runnable {
private String location = "";
private Thread t;
private String threadName;

public MainWatch(String l, String threadName) {
location = l;
this.threadName = threadName;
}

public void start() {
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}

@Override
public void run() {
Where.add(location);
}
}

如何让这两个线程访问主线程上的 where 变量,以便两者都可以访问它?

谢谢!

最佳答案

首先,您需要为您的帖子提供列表链接。为此,您可能需要将 where 设为静态字段。

其次,您需要同步对列表的访问,以免出现 ConcurrentModificationException

private static List<String> = new ArrayList<>();

public static void main(String[] args) {
MainWatch R1 = new MainWatch("C:\\test", "Thread1", where);
R1.start();
MainWatch R2 = new MainWatch("C:\\test2", "thread2", where);
R2.start();
}

public class MainWatch implements Runnable {
...
private final List<String> where;

public MainWatch(String loc, String ThreadName, List<String> where) {
location = loc;
this.threadName = threadName;
this.where = where;
}

...
@Override
public void run() {
synchronized(where) {
where.add(location);
}
}
}

关于java - 如何从两个单独的线程更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38922313/

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