- 線程分為守護(hù)線程和用戶線程
- 虛擬機(jī)需要保證用戶線程執(zhí)行完畢,但不需要守護(hù)線程執(zhí)行完畢
- 守護(hù)線程有后臺操作日志,垃圾回收等待,監(jiān)控內(nèi)存等
代碼示例
注意:一定要先設(shè)為守護(hù)線程,再啟動(dòng)線程,否則將默認(rèn)為用戶線程,由于條件為true,則會(huì)一直執(zhí)行下去。
public class protect { public static void main(String[] args) { God god = new God(); User user = new User(); Thread thread = new Thread(god); thread.setDaemon(true); //設(shè)定為守護(hù)線程,默認(rèn)為false thread.start(); Thread thread2 = new Thread(user); thread2.setPriority(10); thread2.start(); } } // 守護(hù)線程對象 class God implements Runnable { @Override public void run() { while (true) {//虛擬機(jī)不必等待守護(hù)線程結(jié)束 System.out.println("+++++++++++++++++++++++++++"); System.out.println("每天都很安全,開心和幸福"); System.out.println("+++++++++++++++++++********"); } } } // 用戶線程 class User implements Runnable{ @Override public void run() { for(int i = 1; i <=100; i ++){ System.out.println("今年也有好好學(xué)習(xí),好好生活"); System.out.println("開心幸福平安的過完了這一年"); } System.out.println("輕輕的我走了,開啟新的輪回,新的人生"); } }