为什么下面的代码在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;
}
}
最佳答案
这是SE 7中Thread的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 eitherhave to disallow cloning or give it meaningful semantics - and thelatter isn't going to happen."-David Holmes