为什么下面的代码在JDK7中抛出CloneNotSupportedException但在JDK6中?
public class DemoThread extends Thread implements Cloneable {
/**
* @param args
*/
public static void main(String[] args) {
DemoThread t = new DemoThread();
t.cloned();
}
public DemoThread cloned()
{
try {
return (DemoThread) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:6)
这是Thread在SE 7中clone()
的实现
/**
* 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();
}
线程从未被设计为克隆。做一些阅读引发了我发现的一条评论,这总结得很好:"But we either have to disallow cloning or give it meaningful semantics - and the latter isn't going to happen." - David Holmes
答案 1 :(得分:3)
这不起作用,因为无法克隆线程。代码的第16行尝试克隆未实现Cloneable接口的超类(Thread)。除了克隆线程之外根本不是一个好主意。您需要创建一个新线程。这是唯一可行的解决方案。