我的代码有问题。代码即将找到网关/子网,如果程序找到网关/子网,它会将其返回给一个名为"call()“方法的类。这部分工作正常,但问题是我想传递网关的ID (如果网关是192.168.1.1,它也会将数字1传递给填充已创建网关向量的类)。问题是,由于某种原因,保存网关ID的向量是空的。你能告诉我怎么解决问题吗?诚挚的问候。下面是我在项目中使用的代码:
int GateWayKey = 1;
int GateWayKeyStop=254;
String ip="";
StoredGW FoundedGW = new StoredGW();
int SubNetKey = 2;
int SubNetKeyStop = 254;
Vector <Integer> AllGateWays= new Vector <Integer>();
Vector <Future<String>> AllSQLs = new Vector <Future<String>>();
final int NUM_THREADS = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
public void run() {
for (;GateWayKey<=GateWayKeyStop;GateWayKey++){
ip="192.168."+GateWayKey+".1";
AllSQLs.add(exec.submit((new PingTask(ip,GateWayKey))));
}
AllGateWays = FoundedGW.GiveMeGWs();
for (int j : AllGateWays){
for (;SubNetKey<=SubNetKeyStop;SubNetKey++){
ip="192.168."+j+"."+SubNetKey;
AllSQLs.add (exec.submit(new PingTask(ip,null))));
}
exec.shutdown();
}下面是预先生成网关的点击和存储ID的类:
public class PingTask implements Callable <String> {
String ips;
int GateWay;
public PingTask (){
}
public PingTask (String ip, int GateWayKey){
ips=ip;
GateWay=GateWayKey;
}
public String call(){
InetAddress address;
try {
address = InetAddress.getByName(ips);
try {
if (address.isReachable(5000)) {
StoredGW GWs = new StoredGW();
GWs.addNewGW(GateWay);
} else {
return null;
}
} catch (IOException e) {
return null;
}
} catch (UnknownHostException e) {
return null;
}
}
}这里是我存储GateWays的类
public class StoredGW {
Vector <Integer> AllFoundedGWs= new Vector<Integer>();
public void addNewGW(int i){
AllFoundedGWs.add(i);
}
public Vector<Integer> GiveMeGWs(){
return AllFoundedGWs;
}
}发布于 2013-01-18 12:25:11
问题在于:
StoredGW GWs = new StoredGW();
GWs.addNewGW(GateWay);创建一个新的StoreGW (作为局部变量),然后丢弃它。使用吧,FoundedGW。您必须确保它对您的任务是可见的,您可能必须将它作为构造函数参数传递,以便它可以在您的任务中使用。
试试这个:
public class PingTask implements Callable <String> {
String ips;
int GateWay;
StoredGW store;
public PingTask (){
}
public PingTask (String ip, int GateWayKey, StoredGW store){
ips=ip;
GateWay=GateWayKey;
this.store = store;
}
public String call(){
InetAddress address;
try {
address = InetAddress.getByName(ips);
try {
if (address.isReachable(5000)) {
store.addNewGW(GateWay);
} else {
return null;
}
} catch (IOException e) {
return null;
}
} catch (UnknownHostException e) {
return null;
}
}
}然后你可以这样称呼它:
AllSQLs.add(exec.submit((new PingTask(ip,GateWayKey, FoundedGW))));作为一个不相关的附带说明,您需要查看一下Java命名约定标准,它将使您的代码更容易被其他人理解。
https://stackoverflow.com/questions/14398844
复制相似问题