线程优先级
线程优先级代表着线程抢占CPU的概率,优先级越高越有可能抢占到CPU。不一定优先级越高的线程就先执行,只是代表概率。
线程优先级在1~10之间。
package com.yf.demo04;
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
t1.setPriority(1);
t1.start();
t2.setPriority(4);
t2.start();
t3.setPriority(10);
t3.start();
// t4.setPriority(-1);
// t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保守护线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 守护线程如后台记录操作日志,监控内存,垃圾回收等等
package com.yf.demo04;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
Thread thread1 = new Thread(god);
People people = new People();
Thread thread2 = new Thread(people);
//守护线程,默认为false
thread1.setDaemon(true);
thread1.start();
thread2.start();
}
}
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝一直都在");
}
}
}
class People implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你的第"+i+"天");
}
System.out.println("goodbye! world");
}
}