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

时间:2016-08-12 16:09:08

标签: java multithreading

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

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变量才能访问它?

谢谢!

1 个答案:

答案 0 :(得分:2)

首先,您需要为线程提供指向列表的链接。为此,您可能希望将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);
        }
    }
}