How can two threads interact while both work?

I tried to teach myself concurrency, and I had a problem. I understand that two Java threads can interact with each other via wait() and notify() . However, this requires that one thread be inactive and, in fact, "just sit" until the other wakes him up.

Is it possible for both threads to run simultaneously and still listen to notifications from the other? Will this be achieved using concurrency methods or instead of something like an ActionListener ?

For example, the project in which I am testing this is basically a grid in which different objects move around different cells. When two of the entities randomly wander into the same cell, I would like one of them to notify the other about it, and something else will happen on its basis (for example, the greeting: "Hello!"). But in its current form, with the wait / notify paradigm, one of the threads / entities should just sit in one cell, waiting for someone to roam; they cannot get along.

+4
source share
5 answers

There are several ways to interact between threads. Using the most common approach, you can use instance variables to exchange information between threads, but you should only care about writing from a single thread or synchronize any updates with a shared variable. Alternatively, you can use the I / O streams in the stream that were designed for inter-thread communication or transfer raw data between streams. One thread writes information to the stream, and the other reads it.

Here is an example of a method that will read the output from a slow network connection and upload it to System.out using streams.

  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 looks like you want an event callback mechanism when one thread (UI thread) is notified when another thread detects a specific condition. Depending on your platform, most of this is baked. Using Android, for example, you can have a stream that defines the movement of a grid object. It will send an update to the main UI thread to redraw the screen. Such an update may 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 case, you have a background thread that determines the position of all screen elements and notifies the main thread when the positions of the positions change. There is an extracted method that determines if 2 points are random or the same.

+4
source

You can use the Erlang language for securely safe among Processes , which works inside its own address space along with Java as the best and most secure alternative to threading.

+1
source

I tried to teach myself concurrency, and I had a problem. I understand that two Java threads can communicate with each other via wait () and notify ().

Classical Java thread tutorials teach you to wait / notify early on. Back around Java 1.1, 1.2 is the time frame that everything was.

However, if you can get a copy of Brian Goetz’s excellent “Java Concurrency in Practice”, wait / notify is not discussed until chapter 14, “Creating Custom Synchronizers,” in section IV of the extended topics. I'm seriously rephrasing here, but the impression I got was “Well, if you read the 300 previous pages, and none of the building blocks discussed so far matches your needs, then you can try to create your own using wait / notify "

My point is that wait / notify, although very important, may not be the best place to start learning concurrency. Some of the answers / comments in this question (producer / consumer, ExecutorService) relate to the higher levels of Concurrency that were added in Java 5. Although this material was added later, this is the material you should study first.

Back to your question - here are a few thoughts:

If this is a GUI application and you want the background thread to do some work, check out SwingWorker . I had success using SwingWorker (section 9.3.3), where the background thread reads messages from the blocking queue (section 5.3), does some work, and notifies the GUI thread by invoking a higher-level publish method. No "wait / notify" - at least not in my code.

If the application is not based on Swing, and you want different threads to perform tasks in parallel and sometimes send messages to each other, consider ZeroMQ "A socket library that acts like a Concurrency framework." In ZeroMQ, each thread starts an event loop that reads and processes messages. A thread can schedule work on its own thread by sending itself a message. It can schedule work / notify another thread by sending a message to this thread (socket).

Anyway, good luck.

+1
source

Try using the ThreadManager class, which has a List<Thread> and seems to be a semaphore object. Your threads should be able to find and reference other threads from there.

0
source

Is it possible for both threads to run simultaneously and still listen to notifications from the other?

Whenever they are not waiting, they can do something at the same time. If they just seem to be awaiting each other, you will probably be better off with a single thread. (Using multiple threads is not always better)

Will this be achieved using concurrency methods or instead of something like an ActionListener?

This is most likely a design issue with how you violated this issue. Threads work best when there is a minimum of interaction between them. If they are highly dependent on each other, you should consider using fewer threads.

But since this means that with the wait / notify paradigm, one of the threads / entities should just sit in one cell, waiting for someone to roam,

I do not understand why you need to wait / notify here at all. I would just make them move and send messages to each other when they are in the same cell.

0
source

Source: https://habr.com/ru/post/1437234/


All Articles