2014-10-09 86 views
0

我有3个类1.主2.主3.客户(三个实例)。主服务器和客户端有一个函数增量,它们保持递增值,并且定期客户端(比如每2秒)将该增量值发送给主服务器,并且随机时间每个客户端应该随机发送消息给其他客户端(比如client1发送给客户端2)。当maser收到消息时,它会做一些计算并将价值广播给所有消费者。线程之间如何通信

主要-------->

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

} 
} 

大师----->

公共类硕士继承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); 
} 

} 

客户端 - >

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

线程之间的通信是完成/讨论当线程在同一进程中。套接字用于机器间通信(通常)。你在哪一类?你将两者混合在一起。 – SingleStepper 2014-10-09 20:41:30

+0

我只需要在一台机器上模拟这个 – 2014-10-09 20:44:36

+1

声音太复杂了,对我来说这代表糟糕的设计。我可以看到客户与主人沟通,但他们为什么要互相交谈?理想情况下,您希望线程尽可能地独立,并且可能只共享一些数据,而不是在它们之间来回发送消息。 – ventsyv 2014-10-09 20:46:26

回答

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 
}