目录
(一)守护线程
守护线程:守护其他被守护线程。在java中分为守护线程和被守护线程,如果不设置为守护线程,默认为被守护线程。
如果被守护线程全部结束,那么守护线程也结束。
GC就是一个守护线程。
通过setDaemon(true)设置线程为守护线程
public class DaemonDemo {
public static void main(String[] args) {
Monster mon = new Monster();
Thread th1 = new Thread(mon,"小怪A");
Thread th2 = new Thread(mon,"小怪B");
Thread th3 = new Thread(mon,"小怪C");
//设置线程为守护线程
th1.setDaemon(true);
th2.setDaemon(true);
th3.setDaemon(true);
//开启线程
th1.start();
th2.start();
th3.start();
//主线程为守护线程,每一个程序中,即使不创建线程,也会有一条线程被创建。
for (int i = 100; i >= 0; i--) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("BOSS还有"+i+"滴血");
}
}
}
/**
* 创建怪物类,用来作为守护线程
*/
class Monster implements Runnable{
@Override
public void run() {
//设置每个小怪都有500滴血
for(int i = 500; i >= 0; i--){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"还有"+i+"滴血");
}
}
}
部分结果截图:
分析:
从结果中可以看出,等到被守护进程结束之后,守护进程也随之结束。
其次,开启四个自定义线程作为守护线程,让main方法中的线程作为被守护线程(默认),重所周知,当启动一个程序的时候,自动开启一个线程去执行main方法中的线程。
(二)线程的优先级
线程的优先级:默认线程有1-10个优先级。理论上优先级越高,抢到资源的概率就越大,但是实际上相差的结果并不大。
通过setPriority()方法设置
public class PriorityDemo {
public static void main(String[] args) {
PriorityTest pt = new PriorityTest();
Thread th1 = new Thread(pt,"线程A");
Thread th2 = new Thread(pt,"线程B");
Thread th3 = new Thread(pt,"线程C");
th1.setPriority(1);
th2.setPriority(5);
th3.setPriority(9);
th1.start();
th2.start();
th3.start();
}
}
class PriorityTest implements Runnable{
@Override
public void run() {
for(int i = 10; i > 0; i--){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行了");
}
}
}
设置线程C的优先级最高,线程B的优先级其次,最后是线程A。
(三)线程的生命周期
出生 就绪 运行 阻塞 消亡
就绪可以到运行,运行不可以到就绪
运行可以到阻塞,阻塞不可以到运行
就绪可以到阻塞,阻塞可以到就绪