我正在研究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 :(得分:0)
我通过在共享对象 tracker 中存储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);
}