【问题标题】:Get Object instancied by other class in Java获取Java中其他类实例化的对象
【发布时间】: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 以获取一些有用的提示,了解如何以能够为您提供更好帮助的方式发布代码。祝你好运。
  • 现在添加代码,谢谢。
  • 你快到了。你能确保至少发布整个类和方法吗?例如,在您的第二个区块中,我不清楚这是RunnableThreadrun 方法还是其他方法。我会检查的。
  • 请具体说明您遇到问题的那一行。
  • 是的,这个类实现了 Runnable。我添加了完整的类代码。

标签: java multithreading object


【解决方案1】:

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

public class Output implements Runnable {

private Socket client;
private District district;

Output(Socket client, District district) {
    this.client = client;
    this.district = district;
}

【讨论】:

  • 哦!我很尴尬......这是一个很好的选择,我以前没有考虑过这个。但是,如果我有多个不同类型的对象,通过相同的输出发送,它的工作原理?我也需要为同一个客户发送另一个对象。在另一个讨论中:stackoverflow.com/questions/12910350/… 这家伙在客户端/服务器之间引用模块,这对我来说也很有意义,因为我为许多客户端发送相同的对象,而这个客户端也为其他客户端与服务器一起工作。
  • 而且,如果我使用套接字客户端创建了一次输出类,我想不一定每次我需要发送新对象时都创建...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多