从永远到永远-多线程(三)-Daemon、Priority

1、Daemon

1、应用场景

daemon线程应用的业务场景,应用到daemon的业务场景:设备与主站通讯,会创建长连接,之后会有一个心跳检测。如果因为某些原因,连接断开了。那么也不需要心跳检测了。如果不将心跳检测设置为daemon,创建连接的线程死掉后,心跳检测会继续运行,导致资源无法释放!

2、代码模拟

/**
 * @ClassName DaemonThread
 * @Description 
 * @Author WL
 * @Date 2020/8/23 1:07
 */
public class DaemonThread {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println("t is running!");
            try {
                Thread.sleep(10_1000);//jdk1.7后的写法
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t is finished!");
        });
        /**
         * 1、必须在start前设置,否则报异常
         * 2、t被设置为守护线程后,t会随着主线程(调用它的线程)结束而结束。
         */
        t.setDaemon(true);
        t.start();

        System.out.println("main is finished!");
    }
}

3、注意

  • 1、必须在start前设置,否则报异常
  • 2、t被设置为守护线程后,t会随着主线程(调用它的线程)结束而结束。

2、Priority

线程优先级设置,只是尽量根据优先级执行,不保证!

public class PriorityThread {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                Optional.of(Thread.currentThread().getName() + "----" + i).ifPresent(System.out::println);
            }
        }, "Thread 1");
        t1.setPriority(Thread.MAX_PRIORITY);//设置最高优先级
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                Optional.of(Thread.currentThread().getName() + "----" + i).ifPresent(System.out::println);
            }
        }, "Thread 2");
        t2.setPriority(Thread.NORM_PRIORITY);//设置普通优先级
        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                Optional.of(Thread.currentThread().getName() + "----" + i).ifPresent(System.out::println);
            }
        }, "Thread 3");
        t3.setPriority(Thread.MIN_PRIORITY);//设置最低优先级
        t1.start();
        t2.start();
        t3.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值