Java多线程——线程优先级与守护线程

线程优先级

Modifier and TypeField and Description
static intMAX_PRIORITY线程可以拥有的最大优先级。1
static intMIN_PRIORITY线程可以拥有的最小优先级。5
static intNORM_PRIORITY分配给线程的默认优先级。10
  • 可以通过 setPriority 来设定优先级1~10
  • 可以通过getPriority 来获取线程优先级
package com.thread.demo;

public class Demo15 {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();
        MyThread thread4 = new MyThread();
        MyThread thread5 = new MyThread();

        thread1.setName("1号线程");
        thread2.setName("2号线程");
        thread3.setName("3号线程");
        thread4.setName("4号线程");
        thread5.setName("5号线程");

        System.out.println(Thread.currentThread().getName()+"---->"+Thread.currentThread().getPriority());

//       先设置优先级再启动!!,优先级只会增加线程的权重,并不一定绝对会优先执行
        thread1.setPriority(Thread.MIN_PRIORITY);//MIN_PRIORITY=1
        thread2.setPriority(Thread.NORM_PRIORITY);//NORM_PRIORITY=5
        thread3.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        thread4.setPriority(4);
        thread5.setPriority(8);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println(getName()+"---->"+getPriority());
    }
}

守护线程

  • 线程可分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如,后台登录操作日志,监控内存,垃圾回收(gc)等…
package com.thread.demo;

public class Demo16 {
    public static void main(String[] args) {
        God god = new God();
        Thread thread = new Thread(god);
        thread.setDaemon(true);  // 设置为守护线程,默认为false
        thread.start(); // 开启守护线程
//        创建并开启用户线程
        Person person = new Person();
        new Thread(person).start();
    }
}

class Person implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i <= 36500; i++) {
            System.out.println("快乐的活着,每一天 -->" + i + "天");
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("--==========Good bye World~==========--");
    }
}

class God implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("--上帝守护着你--");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pointer-faker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值