java - 无法克隆线程 - 为什么?
问题描述
据我了解,以下代码应生成本地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();
}
克隆线程只是没有意义。
推荐阅读
- php - PHP - 根据 CSV 中的第一个值创建一个数组
- python - Python 2 到 Python 3:TypeError:“模块”对象不可调用
- reactjs - “sh:1:react-scripts:未找到”在 Docker 中
- java - 如何将此 EgienVector 代码 Python 代码实现为 Java
- java - 无法创建 Spring Boot 启动项目:不可解决
- python - 如何控制一个 html 中显示的项目数?
- javascript - 有条件地隐藏所有帖子上的 div,但不隐藏类别页面
- infinispan - 用于集群企业应用程序的 jboss 数据网格 - 什么是有效的方法
- android - 如何在 appcelerator android 应用程序中显示 admob 广告
- react-native - 反应原生线性渐变