开发者

How can 2 threads communicate each other?

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开发者_Go百科 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)?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜