【发布时间】:2015-06-21 02:56:06
【问题描述】:
我有一个问题:在主类中我创建了一个对象
District d = new District(district, sequence);
这个主类创建另一个线程。
这个线程在访问对象的实例时不能这样做,只有当变量是静态的,因为如果不是,就会出现这个消息:非静态变量不能从静态上下文中引用。
我的问题是:我不能使用静态字段,而且我在 Main 类中有一个无限循环,即我也不能使用 get 方法。
如何访问主类中创建的对象?或者,另一方面,为什么我不能使用非静态字段访问参数?
请尽可能考虑除此之外的任何解决方案,甚至创建新的类/方法/变量。
Output output = new Output(client);
Thread to = new Thread(output);
to.start();
++i;
}
while(true){
for(i = 0; i < neighborhood.size(); ++i){
//rand.nextInt((max+1) - min) + min;
Edge edge = new Edge(id, neighborhood.get(i),
rand.nextInt((10 + 1) - 1) + 1);
district.add(edge);
}
District d = new District(district, sequence);
++sequence;
Thread.sleep(5000);
}
还有线程:
public class Output implements Runnable {
private Socket client;
// Construtor do metódo
Output(Socket client) {
this.client = client;
}
@Override
public void run() {
// Obtendo os objetos de controle do fluxo de comunicação
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(client.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Input.class.getName()).log(Level.SEVERE, null, ex);
}
while(true){
District district = new District(District.district, District.sequence);
try {
output.writeUnshared(district);
System.out.println("Objeto enviado");
output.flush();
output.reset();
} catch (IOException ex) {
Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
谢谢。
【问题讨论】:
-
很抱歉您在没有任何解释的情况下投了很多票。但这可能是因为您没有发布遇到问题的代码。拥有要检查的实际代码非常重要。阅读this 以获取一些有用的提示,了解如何以能够为您提供更好帮助的方式发布代码。祝你好运。
-
现在添加代码,谢谢。
-
你快到了。你能确保至少发布整个类和方法吗?例如,在您的第二个区块中,我不清楚这是
Runnable或Thread的run方法还是其他方法。我会检查的。 -
请具体说明您遇到问题的那一行。
-
是的,这个类实现了 Runnable。我添加了完整的类代码。
标签: java multithreading object