繁体   English   中英

销毁线程时是否销毁了变量?

[英]When a Thread is destroyed are the variables destroyed?

我想通过2个线程处理Queue的元素,并按与输入相同的顺序准备OutputQueue。 我仍然必须做一些同步块,但是我仍然遇到以下问题。

  1. 返回空的OutputQueue
  2. 我这样做正确吗?

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

销毁线程时是否销毁了变量?

run()方法调用终止时,线程堆栈将被丢弃,并且线程对其Runnable的引用将为空。 到那时,所有run()方法的局部变量都将超出范围。

Runnable变得不可访问时,将对其进行垃圾收集。 GC最终将“破坏” Runnable的实例变量。


我这样做正确吗?

我将使用ExecutorService ,并通过创建由submit(...)方法返回的Future对象的列表来处理对输出进行排序的问题。

在您的代码中,您似乎有三个不同的HeavyWorkRunnable实例,并且您似乎正在从没有传递给线程的实例中检索输出队列。 在我看来,这并不正确。 共享输入队列上的同步(缺少)也存在问题。 这可能会导致竞争状况和内存可见性问题。

返回空的OutputQueue

是。 这是上述“三个实例”问题的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM