image.png

    1. package com.pln.state;
    2. //测试守护线程
    3. public class TestDaemon {
    4. public static void main(String[] args) {
    5. God god = new God();
    6. You you = new You();
    7. Thread thread = new Thread(god);
    8. thread.setDaemon(true);//默认是false表示是用户线程,正常的线程都是用户线程,true开启守护线程
    9. thread.start();
    10. new Thread(you).start();
    11. }
    12. }
    13. class God implements Runnable{
    14. @Override
    15. public void run() {
    16. while (true){
    17. System.out.println("上帝保护着你");
    18. }
    19. }
    20. }
    21. class You implements Runnable{
    22. @Override
    23. public void run() {
    24. for (int i = 0; i < 20000; i++) {
    25. System.out.println("一生都开心的活着");
    26. }
    27. System.out.println("---------------GoodBuy!World---------------");
    28. }
    29. }