线程优先级
Modifier and Type | Field and Description |
---|
static int | MAX_PRIORITY 线程可以拥有的最大优先级。1 |
static int | MIN_PRIORITY 线程可以拥有的最小优先级。5 |
static int | NORM_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);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);
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);
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();
}
}
}
}