2个线程如何相互通信?
线程 A
正在汇总从 10 个客户端传递的数据。
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;
}
}
线程 B
不断地与客户端通信,无论它们是否还活着(心跳技术)。
问题是客户端有时可能会失败,在这种情况下,汇总数据的线程应该只打印出活动客户端的所有可能结果。否则,它永远不会打印结果。
那么,如果心跳线程注意到一个客户端没有响应,是否有一种方法可以告诉另一个线程(或更改其他线程的类变量 this.left
)?
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
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上,线程通信有两种通用方法:
在共享内存方法中,您可以创建两个线程都可以读取和写入的同步列表或同步映射。通常,要确保读取和写入不发生冲突,会产生一些开销,例如,您不希望正在读取的对象在读取时被删除。 Java 提供了行为良好的集合,例如
Collections.synchronizedMap
和Collections.synchronizedList
。在事件或基于队列的线程通信中,线程具有传入队列并写入其他线程的传入队列。在这种情况下,您可能让心跳线程加载一个包含要读取的客户端的队列,并让其他线程轮询/从该队列获取数据并进行处理。心跳线程可以不断地将活动的客户端添加到该队列中,以便处理线程“知道”继续处理它们。
Basically, there are two general approaches to thread communication:
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
andCollections.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.