VinnieS
VinnieS

Reputation: 85

How to update an array from two separate threads

I am running two separate threads:

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();
}

I want both of them to update the where array:

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);
    }
}

How do I get those two threads to access the where variable on the main thread to both have access to it?

Thanks!

Upvotes: 0

Views: 390

Answers (1)

Andrew Lygin
Andrew Lygin

Reputation: 6197

First, you need to provide your threads with links to your list. To do that, you might want to make where a static field.

Second, you need to synchronize access to the list in order not to get 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);
        }
    }
}

Upvotes: 2

Related Questions