【问题标题】:How can i access the same Stack in two different Classes?如何在两个不同的类中访问相同的堆栈?
【发布时间】:2020-11-24 05:11:46
【问题描述】:

我有两种不同的方法来启动线程。现在我想要第一个 run() 方法在这个堆栈上添加元素,第二个 run() 方法从同一个堆栈中弹出元素。如何在两个不同的类中访问同一个 Stack? 我应该在 run() 方法还是线程正在运行的方法中添加和删除元素?

run 方法创建我想要添加到堆栈的对象。

这是我的主类中线程代码的一部分:

public static void startProducers(int producerCount)
{
    for (int i = 0; i < producerCount; i++ ) {
        Thread counter = new Thread(new Producer(i));
        counter.start();
    }

}

public static void startUsers(int UserCount)
{
    for (int i = 0; i < UserCount; i++ ) {
        Thread counter1 = new Thread(new User(i));
        counter1.start();
    }
}

【问题讨论】:

  • 我为每个用户和生产者创建一个线程,因为每个线程都应该在运行方法中产生/删除对象。 Stack 包含在生产者运行方法中生成的对象。能否举例说明如何使用 mStack 作为成员字段?

标签: java multithreading stack


【解决方案1】:

我们可以在两个线程类中传递相同的堆栈对象。像这样的

class Thread1 extends Thread {
    Thread1(Stack s) {}
    method run() {// push in the same stack object}
}

class Thread2 extends Thread {
    Threa2(Stack s) {}
    method run() {// pop from the same stack object}
}

如果您可以通过添加一些示例来详细说明您编写的代码,那将有很大帮助! 谢谢:)

【讨论】:

  • 感谢您的快速回复,我编辑了上面的代码。我不知道如何在两个不同的运行方法中访问同一个 Stack,所以我可以从 Stack 中推送和弹出对象。
  • 如果我在我的 Thread 方法中使用 Stack,我怎样才能得到我的生产者运行方法中产生的 Object?
  • 如果上述两个方法在同一个类中,那么很容易做到。只需在该类(堆栈)中添加一个新字段并访问它。
猜你喜欢
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多