Java 如何在线程之间通信

Java 如何在线程之间通信,java,multithreading,sockets,Java,Multithreading,Sockets,我有三个班。主要内容2。大师3。客户端(三个实例)。Master和client有一个函数increment,在该函数中,它们保持一个增量值,并定期(比如每2秒)将该增量值发送给Master,并且在随机时间,每个客户端都应该向随机选择的其他客户端发送消息(比如client1发送给客户端2)。当微波激射器接收到信息时,它将进行一些计算,并将值广播给所有的cilent 主要----------------> 大师------> 公共类主线程扩展{ private int inc= 0; long st

我有三个班。主要内容2。大师3。客户端(三个实例)。Master和client有一个函数increment,在该函数中,它们保持一个增量值,并定期(比如每2秒)将该增量值发送给Master,并且在随机时间,每个客户端都应该向随机选择的其他客户端发送消息(比如client1发送给客户端2)。当微波激射器接收到信息时,它将进行一些计算,并将值广播给所有的cilent

主要---------------->

大师------>

公共类主线程扩展{

private int inc= 0;
long start = System.currentTimeMillis();
long end = start + 10*1000; 
Socket socket;

Master(Socket socket){
    this.socket = socket;
}

@Override

public void run() {

    while(System.currentTimeMillis() < end){
        increment();

    //Method to read input from the client 

      }

}

private void increment(){   
    inc++;
    System.out.println("counter"+ inc);
}

}
private int inc=0;
长启动=System.currentTimeMillis();
长端=起点+10*1000;
插座;
主机(插座){
this.socket=socket;
}
@凌驾
公开募捐{
while(System.currentTimeMillis()
客户-->

公共类客户端扩展线程{
私人国际公司=0;
长启动=System.currentTimeMillis();
长端=起点+10*1000;
公开募捐{
while(System.currentTimeMillis()

我走的是当前的道路吗??如何连接主机和客户端以及客户端与其他客户端??插座是否是唯一的方法??我是新手。

最好的办法可能是使用管道。以PipedInputStream和PipedOutStream类为例。打开管道后,要接收数据,请执行以下操作:

//establish the pipe connection

while (pipe) //assuming someone will eventually close the connection
{
   while (pipe.available() > 0)
      buffer.addByte(pipe.read())

   //Do some other processing
}

线程之间的通信在线程处于同一进程时完成/讨论。插座用于机器间通信(通常)。你属于哪一类?你把两者混在一起了。我需要在一台机器上模拟这一点,但声音太复杂了,这对我来说意味着糟糕的设计。我可以看到客户们和师父来回交流,但他们为什么要互相交谈呢?理想情况下,您希望线程尽可能独立,并且可能只共享一些数据,而不是在它们之间来回发送消息。“智能套接字”类似于ZeroMQ或nanomsg,是非常强大的工具,可以帮助您设置/使用进程到进程消息层。在开始使用错误的多线程/多进程/多主机通信体系结构之前,沃斯花一周时间通读这本书。Python和许多其他编程语言的端口/绑定/包装器可用于ZeroMQ,有些还可用于nanomsg。@ventsyv这是必需的。客户应该相互交流。我可以使用Pipedstream进行线程间通信吗?
    public class Client extends Thread  {

    private int inc= 0;
    long start = System.currentTimeMillis();
    long end = start + 10*1000; 

     public void run() {

    while(System.currentTimeMillis() < end){
        increment();

    //Method to send the value to the Master or other clients


      }

      }

     private void increment(){  
    inc++;
    System.out.println("counter"+ inc);
    }

     }
//establish the pipe connection

while (pipe) //assuming someone will eventually close the connection
{
   while (pipe.available() > 0)
      buffer.addByte(pipe.read())

   //Do some other processing
}