首页 > PHP资讯 > JAVA培训 > 线程守护

线程守护

JAVA培训

守护线程:

一个线程可以调用void setDaemon(Boolean on)方法,将自己设置称为一个守护线程,如:

thread.setDaemon(ture);想默认实非守护的,也称为用户线程。当程序中的所有线程都已结束运行时,即使守护线程中的run()方法还有需要执行的语句,守护线程也立刻结束运行。一般,用守护线程做一些不是很严格的事情,线程的随时结束不会产生什么不良的结果,一个线程必须在运行之前设置自己是否为守护线程。

public class Deamon implements Runnable {
       Thread A,B;
       public Deamon() {
              A = new Thread(this);
              B = new Thread(this);
       }
       public void run() {
              if (Thread.currentThread() == A) {
                     for (int i = 0; i < 8; i++) {
                            System.out.println("i="+i);
                            try {
                                   Thread.sleep(1000);
                            } catch (Exception e) {
                                   e.printStackTrace();
                            }
                     }
              } else {
                     while(true){
                            System.out.println("线程B是守护线程!");
                            try {
                                   Thread.sleep(1000);
                            } catch (Exception e) {
                                   e.printStackTrace();
                            }
                     }
              }
       }
}

public class TestDeamon {
       public TestDeamon() {
       }
       public static void main(String[] args) {
              Deamon a = new Deamon();
              a.A.start();
              a.B.setDaemon(true);
              a.B.start();
       }
}

常州java培训机构

上一篇:线程联合
本文由欣才IT学院整理发布,未经许可,禁止转载。