守护进程
当其他的非守护线程执行完毕之后,守护线程会陆续结束
通俗易懂:当女神线程结束了,那么备胎也没有存在的必要了
package multithread.guard;
public class GuardThread1 extends Thread{
@Override
public void run() {
// 线程执行的代码
for (int i = 0; i < 10; i++) {
System.out.println(getName() + " " + i);
}
}
}
package multithread.guard;
public class GuardThread2 extends Thread{
@Override
public void run() {
// 线程执行的代码
for (int i = 0; i < 100; i++) {
System.out.println(getName() + " " + i);
}
}
}
package multithread.guard;
public class ThreadDemo {
public static void main(String[] args) {
GuardThread1 t1 = new GuardThread1();
GuardThread1 t2 = new GuardThread1();
// 设置线程名称
t1.setName("女神");
t2.setName("舔狗");
// 设置守护线程
t2.setDaemon(true);
// 启动线程
t1.start();
t2.start();
}
}
礼让线程
package multithread.comity;
public class ComityThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + "-" + i);
// 线程礼让 表示让出当前CPU的执行权
// 该方法只是表示当前线程愿意让出当前的CPU执行,但是让出的时间不确定,有可能刚刚让出,马上又被CPU
// 调度了
// 礼让后,线程会由RUNNING变为RUNNABLE状态,然后再次等待CPU的调度
// 礼让的目的是让线程有重新竞争获取CPU执行权的权利
Thread.yield();
}
}
}
package multithread.comity;
public class ThreadDemo {
public static void main(String[] args) {
// 创建线程对象
ComityThread t1 = new ComityThread();
ComityThread t2 = new ComityThread();
// 设置线程名称
t1.setName("女神");
t2.setName("男神");
// 启动线程
t1.start();
t2.start();
}
}