java 多线程(daemon)

时间:2023-12-29 20:03:38
package com.example;

public class App {

    public static void main(String[] args) {

        DoDaemon d1 = new DoDaemon();
DoRunnable d2 = new DoRunnable("Sinny"); Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
//设置为后台线程,
t1.setDaemon(true); t1.start();
t2.start();//用户线程结束后,JVM自动退出,不再等待后台进程
}
}
package com.example;

public class DoDaemon implements Runnable{
@Override
public void run() {
for (int i = 0; i < 300; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("Hello__Deamon");
}
}
}
package com.example;

public class DoRunnable implements Runnable {

    private String name;

    public DoRunnable(String name) {
this.name = name;
} @Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("Hello__" + this.name);
}
}
}