gpt4 book ai didi

java - 无法克隆线程 - 为什么?

转载 作者:行者123 更新时间:2023-12-01 06:27:35 27 4
gpt4 key购买 nike

据我了解,以下代码应生成本地 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;
}

}
}

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

最佳答案

看看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();
}

克隆线程没有任何意义。

关于java - 无法克隆线程 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54078047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com