我正在尝试设置一个多线程服务器,为每个线程创建一个图形对象。
我现在遇到的问题是,我不知道如何将图形对象映射到"它""线。
基本上我在<{1}}函数中尝试是调用负责创建球的类addBallToThread
。
我想将这个球映射到该特定线程,然后在线程关闭时最终移除球。
如果有人可以向我展示一个这方面的示例,或者帮助我使用我非常感激的现有代码。
ClientThread:
Graphics
图形:
public class ClientThread extends Thread{
private static int numberOfClients = 0;
protected static ArrayList<ClientThread> allClients = new ArrayList<ClientThread>();
//Create instance of this class for each new client^
private final int clientNumber = ++numberOfClients;
private final Socket socket;
private final BufferedReader in;
private final BufferedWriter out;
private static ArrayList<Graphics> Balls = new ArrayList<Graphics>();
public ClientThread(Socket s) throws IOException {
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("Thread Created For Client: "+clientNumber+"");
System.out.println("Welcome client nr: #"+clientNumber+"");
synchronized (this) {
allClients.add(this); //add thread to new instance of class
addBallToThread(); //connecting ball to thread?
}
start(); //starts thread, calls run
}
//###################### HERE ########################
public void addBallToThread(){
int totalClients = clientNumber;
for(int i=1;i<=totalClients; ++i) {
Balls.add((Graphics) allClients.iterator());
//Creating one Graphics Object for every Client?
}
}
public void run() {
try {
while (true) {
String inline = in.readLine();
System.out.println("BALL NR:"+Balls.size()+"CONNECTED TO: "+clientNumber);
System.out.println("Client thread " + clientNumber + " received: " + inline);
if (inline == null || inline.equals("quit")) break;
System.out.println("You said :" + inline + ".");
Iterator<ClientThread> i = allClients.iterator();
while (i.hasNext()) {
ClientThread t = i.next();
if (t != this)
System.out.print("From client " + clientNumber + ": " + inline);
}
} //while, while
//############# IGNORE, not necessary ###########
System.out.println("Client thread " + clientNumber + ": exiting...");
}
catch(IOException e) {
System.out.println("Client thread " + clientNumber + ": I/O error");
}
finally {
try { socket.close(); }
catch(IOException e) {
System.out.println("Client thread " + clientNumber + ": Socket not closed!");
}
synchronized(this) {
allClients.remove(allClients.indexOf(this));
}
} //finally
} //run
}