我想通过 2 个线程处理 Queue 的元素,并按照与输入相同的顺序准备 OutputQueue。我仍然需要制作一些同步块(synchronized block),但我遇到了以下问题。
- 返回空OutputQueue
- 我这样做的方式正确吗?
ThreadMailClass.java
public class ThreadMainClass {
public static void main(String[] args) {
int[] inputQueue={2,3,4,5,6};
processJobs(inputQueue);
}
public static void processJobs(int[] inputQueue){
Queue<Integer> queue = new LinkedList<Integer>();
for(int i:inputQueue){
queue.add(i);
}
System.out.println("Input Queue Size:" + queue.size());
HeavyWorkRunnable hr = new HeavyWorkRunnable();
Thread t1 = new Thread(new HeavyWorkRunnable(queue),"t1");
Thread t2 = new Thread(new HeavyWorkRunnable(queue),"t2");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//This method is returning empty Queue.
Queue<Integer> outputQueue = hr.getOutputQueue();
System.out.println("Printing Output Queue.." + outputQueue.size());
for(Integer i:outputQueue)
System.out.println(i);
System.out.println("Printing Done");
}
HeavyWorkRunnable.java
public class HeavyWorkRunnable implements Runnable {
private Queue<Integer> outputQueue = new LinkedList<Integer>();
private Queue<Integer> inputQueue;
public HeavyWorkRunnable() {
}
public HeavyWorkRunnable(Queue<Integer> inputQueue) {
this.inputQueue = inputQueue;
}
@Override
public void run() {
System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
try {
processInputQueue();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
}
private void processInputQueue() {
while(inputQueue.peek()!=null){
System.out.println(Thread.currentThread().getName() + "-->input size -->"+ inputQueue.size());
outputQueue.add(inputQueue.remove());
System.out.println(Thread.currentThread().getName() + "-output size -->"+ outputQueue.size());
}
}
public Queue<Integer> getOutputQueue() {
return this.outputQueue;
}
}
最佳答案
When a Thread is destroyed are the variables destroyed?
当run()
方法调用终止时,线程堆栈将被丢弃,并且线程对其Runnable
的引用将被清空。到那时,所有 run()
方法的局部变量都将超出范围。
当Runnable
变得无法访问时,它会被垃圾收集。 GC 最终会“销毁”Runnable
的实例变量。
Am I doing this the right way.
我将使用 ExecutorService
,并通过创建由 submit(... )
方法。
在您的代码中,您似乎有三个不同的 HeavyWorkRunnable
实例,并且您似乎正在从您没有传递给的实例中检索输出队列线。这对我来说看起来不正确。共享输入队列还存在同步(缺乏)的问题。这可能会导致竞争条件和内存可见性问题。
Empty OutputQueue is returned
是的。这是上述“三个实例”问题的结果。
关于java - 当线程被销毁时,变量会被销毁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42605018/