如何在线程之间进行通信

时间:2014-10-09 20:36:39

标签: java multithreading sockets

我有3个班级1.主要2.硕士3.客户(三个实例)。主服务器和客户端有一个函数增量,它们保持增量值,并定期客户端(比如每2秒)将该增量值发送给主服务器,并且随机时间每个客户端应该向其随机选择的其他客户端发送消息(比如client1发送给客户端) 2)。当微波接收到消息时,它将进行一些计算并将值广播给所有cilents。

主要-------->

public class Sample_one{

public static final int PORT = 4444;
public static void main(String[] args) throws IOException{


ServerSocket server = new ServerSocket(PORT);
Socket socket =server.accept();

Thread m1=  new Master(socket);
m1.start();


Client c1 = new Client();
Client c2 = new Client();
Client c3 = new Client();
c1.start();
c2.start();
c3.start();

}
}

大师----->

public class Master extends Thread {

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);
}

}

客户 - &gt;

    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);
    }

     }

我是否会进入当前的道路?如何将主客户端和客户端与其他客户端连接? Socket是否是唯一的方法?我是新的主题。

1 个答案:

答案 0 :(得分:0)

最好的办法就是使用烟斗。例如,查看PipedInputStream和PipedOutputStream类。打开管道后,要接收数据,您可以执行以下操作:

//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
}