“Thread.setDefaultUncaughtExceptionHandler”的构造函数和静态代码有什么区别?功能
构造函数和静态代码有什么区别?
为什么Thread.setDefaultUncaughtExceptionHandler
不能在构造函数中工作?
源代码 1:
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e.getMessage());
}
}
public class CaughtExceptionThread extends Thread{
static {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}
}
源代码 2:
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e.getMessage());
}
}
public class CaughtExceptionThread extends Thread{
public CaughtExceptionThread() {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}
}
测试代码:
public class DefaultExceptionHandler extends CaughtExceptionThread{
public static void main(String[] args) {
ExecutorService es =
Executors.newCachedThreadPool();
es.execute(new ExceptionThread());
es.shutdown();
}
}
为什么源代码 1 可以工作,而源代码 2 却不能?
What is the difference between constructor and static code?
Why Thread.setDefaultUncaughtExceptionHandler
can not work in constructor?
Source code 1:
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e.getMessage());
}
}
public class CaughtExceptionThread extends Thread{
static {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}
}
Source code 2:
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e.getMessage());
}
}
public class CaughtExceptionThread extends Thread{
public CaughtExceptionThread() {
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}
}
Test Code:
public class DefaultExceptionHandler extends CaughtExceptionThread{
public static void main(String[] args) {
ExecutorService es =
Executors.newCachedThreadPool();
es.execute(new ExceptionThread());
es.shutdown();
}
}
Why source code 1 is working but source code 2 is not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论