首页 > 解决方案 > 无法克隆线程 - 为什么?

问题描述

据我了解,以下代码应生成本地ProcessingThread运行的 4 个克隆,产生输出:

processing 0
processing 1
processing 2
processing 3

但是,当我尝试运行该程序时,我得到:

java.lang.CloneNotSupportedException

 public class Test {

    public static void main(String[] args) {
        Test o = new Test();
        try {
            o.process(o.new ProcessingThread() {
                public void run() {
                    System.err.println("processing " + index);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void process(ProcessingThread template) throws CloneNotSupportedException {
        // Try run 4 parallel processing threads from the supplied template...
        for (int i = 0; i < 4; i++) {
            ProcessingThread thread = (ProcessingThread) template.clone();
            thread.setIndex(i);
            thread.start();
        }
        // ...
    }

    public class ProcessingThread extends Thread implements Cloneable {
        int index;

        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        public void setIndex(int i) {
            index = i;
        }

    }
}

请帮我理解这个?以及如何纠正这个问题

标签: javamultithreading

解决方案


只需查看类的源代码Thread

/**
 * Throws CloneNotSupportedException as a Thread can not be meaningfully
 * cloned. Construct a new Thread instead.
 *
 * @throws  CloneNotSupportedException
 *          always
 */
@Override
protected Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}

克隆线程只是没有意义。


推荐阅读