public class ThreadDaemon { /** * @param args * 后台线程在主进程结束后,也会退出 */ public static void main(String[] args) { // TODO Auto-generated method stub ThreadImplementsTest tlt=new ThreadImplementsTest(); Thread t1=new Thread(tlt); t1.setName("Daemon Thread test"); 如果一个进程中只用后台线程在运行,那么整个进程就会结束。 t1.start(); } }
Output:
exit
Daemon Thread test====>进入loop()
0
public class ThreadImplementsTest implements Runnable{ public void loop(){ String name=Thread.currentThread().getName(); System.out.println(name+"====>进入loop()"); for (int i = 0; i < 10; i++) { try { System.out.println(i); Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println(e.getLocalizedMessage()); System.out.println(e.getMessage()); e.printStackTrace(); } } System.out.println(name+"=============>离开Loop"); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ThreadImplementsTest tst=new ThreadImplementsTest(); tst.run(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } tst.loop(); } public void run() { // TODO Auto-generated method stub loop(); } }
时间: 2024-09-11 16:26:26