线程属性
- ID:线程id 从1开始
private static synchronized long nextThreadID() { return ++threadSeqNumber; }
- NAME:线程名称 Thread-
public Thread(ThreadGroup group, Runnable target) { init(group, target, "Thread-" + nextThreadNum(), 0); }
- IS DAEMON:是否是守护线程
线程类型默认继承自父线程
不影响JVM退出
- PRIORITY:优先级。程序设计不应该依赖于优先级
/** * The minimum priority that a thread can have. */ public final static int MIN_PRIORITY = 1; /** * The default priority that is assigned to a thread. */ public final static int NORM_PRIORITY = 5; /** * The maximum priority that a thread can have. */ public final static int MAX_PRIORITY = 10;
线程中的统一异常处理
主线程的异常可以被轻松发现,而子线程异常无法使用传统方式捕获,因为try catch只能捕获所在线程的异常。例如下面无法catch
package com.study.thread.uncatch_exception; public class ExceptionInChildThread implements Runnable{ public static void main(String[] args) { try { new Thread(new ExceptionInChildThread(),"thread1").start(); new Thread(new ExceptionInChildThread(),"thread2").start(); new Thread(new ExceptionInChildThread(),"thread3").start(); new Thread(new ExceptionInChildThread(),"thread4").start(); }catch (RuntimeException e){ System.out.println("我可以捕获吗"); } } @Override public void run() { throw new RuntimeException(); } }
所以我们使用UncaughtExceptionHandler
package com.study.thread.uncatch_exception;
public class MyUncauthExceptionHandler implements Thread.UncaughtExceptionHandler {
private String name;
public MyUncauthExceptionHandler(String name) {
this.name = name;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("模拟保存日志等操作"+t.getName()+e);
}
}
package com.study.thread.uncatch_exception;
public class UserExceptionHandlerDemo implements Runnable{
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler(new MyUncauthExceptionHandler("捕获器"));
new Thread(new UserExceptionHandlerDemo(),"thread1").start();
new Thread(new UserExceptionHandlerDemo(),"thread2").start();
new Thread(new UserExceptionHandlerDemo(),"thread3").start();
new Thread(new UserExceptionHandlerDemo(),"thread4").start();
}
@Override
public void run() {
throw new RuntimeException();
}
}