Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can two threads communicate while both are running?

I've been trying to teach myself concurrency, and I've run into an issue. I understand that two Java threads can communicate to each other via wait() and notify(). However, this requires one thread to be inactive and essentially "just sitting around" until the other one wakes it up.

Is it possible to have both threads running simultaneously and still have them listening for notifications from the other? Would this be accomplished through concurrency techniques or instead something like an ActionListener?

For example, the project I'm testing this on is basically a grid where different entities wander around through different cells. When two of the entities happen to wander into the same cell, I'd like one to notify the other and something different to happen based on this (for instance, a greeting: "Hello there!"). But as it stands, with the wait/notify paradigm, one of the threads/entities has to simply sit in one cell waiting for another to wander in; they can't both move around.

like image 894
asteri Avatar asked Oct 01 '12 16:10

asteri


People also ask

How do two threads communicate with each other?

Inter-thread Communication All the threads in the same program share the same memory space. If an object is accessible to various threads then these threads share access to that object's data member and thus communicate each other. The second way for threads to communicate is by using thread control methods.

Can we communicate between threads?

Thread communicate via shared memory. In Java this is usually via shared Objects such as ArrayBlockingQueue, ConcurrentHashMap, or ExecutorService. These objects can be used in a thread safe manner to share/pass objects between threads.

Can two threads run at the same time?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

How do two threads communicate with each other in C?

Thread which you want to notify of an event like "data available" can register a callback function which can be trigerred by the notifier thread. You can use a function pointer for this. Ex: Thread 2 registers a callback function for one or more events.


1 Answers

There's a few ways you can communicate between threads. Using the most common approach you can use instance variables to share info between threads but you must take care to only write from one thread or synchronize any updates to the shared variable. Alternatively you can use Piped I/O streams which were designed for inter-thread communication, or passing raw data between threads. One thread writes info to the stream while the other reads it.

Here's an example method that would read output from a slow network connection and dump it to System.out using threads.

    public void threads() throws IOException {
    final PipedOutputStream outputForMainThread = new PipedOutputStream();
    new Thread(new Runnable() {
        @Override
        public void run() {
            while(moreDataOnNetwork()) {
                byte[] data = readDataFromNetwork();
                try {
                    outputForMainThread.write(data);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(outputForMainThread)));
    for(String eachLine = reader.readLine(); eachLine != null; eachLine = reader.readLine()) {
        System.out.println(eachLine);
    }
}

However it almost sounds like you want an event callback mechanism where one thread (your user interface thread) is notified when the other thread detects a certain condition. Depending on your platform much of this is baked in. Using Android, for eg., you could have a thread that determines that a grid entity moved. It would send an update to the main user interface thread to repaint the screen. Such an update could resemble:

public void gridEntityDidUpdate(final Point fromLocation, final Point toLocation) {
    Activity activity = getMainActivity();
    activity.runOnUiThread(
            new Runnable() {
                @Override
                public void run() {
                    updateScreen(fromLocation, toLocation);
                    if(pointsAreCoincedent(fromLocation, toLocation)) {
                        System.out.println("Hello there!");
                    }
                }
            }
    );
}

private void updateScreen(Point fromLocation, Point toLocation) {
    //Update the main activity screen here
}

In this scenario you have a background thread that works out the position of all on-screen elements and notifies the main thread when elements positions change. There is an extracted method that determines if 2 points are coincidental or the same.

like image 178
Cliff Avatar answered Nov 24 '22 08:11

Cliff