线程核心之线程属性和线程异常处理

线程属性

  • 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();
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值