How can 2 threads communicate each other?
Asked Answered
M

1

6

Thread A is summing up data passed from 10 clients.

while(true){
    Socket clientfd= server.accept ();
    BufferedReader message = new BufferedReader(new InputStreamReader (clientfd.getInputStream() ) );
    String val = message.readLine();
    this.sum_data+=(message.readLine();
    message.close ();
    clientfd.close ();
    this.left--;
    if(this.left==0){
        System.out.println(this.sum_data);
        break;
    }
}

Thread B is constantly communicating with clients whether they are alive or not (heartbeating technique).

The thing is that clients sometimes can fail, and in that case, thread which is summing up data should just print out the all possible results from alive clients. Otherwise, it will never printout the result.

So, if heartbeat thread notices one client is not responding, is there a way for it to tell the other thread (or change other thread's class variable this.left)?

Meat answered 31/7, 2011 at 1:25 Comment(0)
G
9

Basically, there are two general approaches to thread communication:

  1. Shared memory
  2. Event/queue based

In the shared memory approach, you might create a a synchronized list or a synchronized map that both threads may read from and write to. Typically there is some overhead to making sure reads and writes occur without conflicts, you don't want to have an object you're reading deleted while you're reading it, for instance. Java provides collections which are well behaved, like Collections.synchronizedMap and Collections.synchronizedList.

In event, or queue based, thread communication, threads have incoming queues and write to other thread's incoming queues. In this scenario, you might have the heartbeat thread load up a queue with clients to read from, and have the other thread poll/take from this queue and do its processing. The heartbeat thread could continually add the clients that are alive to this queue so that the processing thread "knows" to continue processing them.

Grosswardein answered 31/7, 2011 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.