2011-11-26 83 views
0

我正在致力于Distributed System,当前状态是更多的客户端/服务器应用程序,因为我错过了使其成为分布式系统的关键部分。我不知道如何实现我的客户端线程类c_thread将“消息”传递给正在运行的所有工作线程w_thread传递给多个线程的消息

import java.net.*; 
import java.io.*; 

public class w_thread extends Thread { 

    private Socket socket = null; 
    private tracker track = null; 
    private int tID; 

    //Constructor method 
    public w_thread(tracker t, Socket s) { 
    super("w_thread"); 
    this.track = t;  
    this.socket = s;    
    tID = track.add(); 
    } 

    public void run() { 
    try { 

     String inputLine, outputLine; 
     PrintWriter worker_out; 
     BufferedReader worker_in; 

     //set up IO to worker 
     worker_out = new PrintWriter(socket.getOutputStream(), true); 
     worker_in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     //Get inputLine from c_thread? 

     //... 

     /* 
     worker_out.close(); 
     worker_in.close(); 
     socket.close(); 
     */ 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 

import java.net.*; 
import java.io.*; 

public class c_thread extends Thread { 

    private Socket socket = null; 
    private tracker track = null; 

    //Constructor method 
    public c_thread(tracker t, Socket s) { 
    super("c_thread"); 
    this.track = t;  
    this.socket = s;   
    } 

    public void run() { 
    try { 

     String inputLine, outputLine; 
     PrintWriter client_out; 
     BufferedReader client_in; 

     //set up IO to client 
     client_out = new PrintWriter(socket.getOutputStream(), true); 
     client_in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

     inputLine = client_in.readLine(); 

     if (track.numOfConnections() == 0) { 
     outputLine = "No resources available!";  
     } 

     else {  
     //send inputline to all w_threads  
     outputLine = "Resources was available!";   
     } 
     client_out.println(outputLine); 

     /* 
     client_out.close(); 
     client_in.close(); 
     //close connection 
     socket.close(); 
     */  

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 

我刚才的问题介绍了什么我想实现:Distributed System

回答

0

我已经通过存储w_threads的数组中的共享对象跟踪解决了这个问题。

private ArrayList<w_thread> threadlist = new ArrayList<w_thread>(); 

这意味着从c_thread类我现在可以访问所有的w_threads。

for(int i=0;i<track.numOfConnections();i++) { 
    worker = track.get_thread(i); 
    worker.sendWork(inputLine); 
}