获取Java中其他类实例化的对象

时间:2015-06-21 02:56:06

标签: java multithreading object

我有一个问题:在主类我创建了一个对象

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);
        }
   }
}

感谢。

1 个答案:

答案 0 :(得分:0)

为什么不将区域作为参数传递给Output构造函数?

public class Output implements Runnable {

private Socket client;
private District district;

Output(Socket client, District district) {
    this.client = client;
    this.district = district;
}
相关问题