我在创建Thread的类中有一个方法,我需要使用Thread of Thread。
public class LocalClient {
/*
* Some Stuff
*/
LocalClientThread thr;
public LocalClient(){
this.setHotes();
for(InetAddress i : thr.getNetwork())
System.out.println(i.getHostAddress()); //no error but write nothing.
}
public void setHotes(){
thr = new LocalClientThread(c);
Thread t = new Thread(thr);
t.start();
}
和我的线程
public class LocalClientThread extends Thread {
List<InetAddress> network = Collections.synchronizedList(new ArrayList<InetAddress>());
DatagramSocket c;
public LocalClientThread(DatagramSocket c){
this.c = c;
}
@Override
public void run(){
while(true){
/* Some Stuff
*/
network.add(receivePacket.getAddress());
}
}
}
/**
* @return the network
*/
public List<InetAddress> getNetwork() {
return network;
}
}
实际上我的线程正确地在列表中添加了所有收到的地址。
但我想在线程完成时使用列表来添加所有地址...... 有任何想法吗 ?
答案 0 :(得分:1)
使用Thread.join()以等待线程结束,然后调用getNetwork()以访问线程刚刚填充的列表。
在您的代码中,这看起来像:
thr = new LocalClientThread(c);
Thread t = new Thread(thr);
t.start();
t.join(); // waits for Thread t to come to end
List<InetAddress> collectedAddresses = thr.getNetwork();