[英]How can i access the same Stack in two different Classes?
我有两种不同的方法来启动线程。 现在我想要第一个 run() 方法在这个堆栈上添加元素,第二个 run() 方法从同一个堆栈中弹出元素。 如何在两个不同的类中访问同一个堆栈? 我应该在 run() 方法中还是在线程运行的方法中添加和删除元素?
运行方法创建我想添加到堆栈的对象。
这是我的 Main Class 中线程代码的一部分:
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();
}
}
我们可以在线程 Class 中传递相同的堆栈 object。像这样
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}
}
如果您可以通过添加一些示例来详细说明您编写的代码,那将有很大帮助:! 谢谢 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.