Java Tutorial/Thread/Daemon Thread

Материал из Java эксперт
Версия от 18:18, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A daemon thread.

   <source lang="java">

class MyDaemon implements Runnable {

 Thread thrd;
 MyDaemon() {
   thrd = new Thread(this);
   thrd.setDaemon(true);
   thrd.start();
 }
 public boolean isDaemon(){
   return thrd.isDaemon();
 }
 public void run() {
   try {
     while(true) {
       System.out.print(".");
       Thread.sleep(100);
     }
   }
   catch(Exception exc) {
     System.out.println("MyDaemon interrupted.");
   }
 }

} public class Main {

 public static void main(String args[]) throws Exception{
   MyDaemon dt = new MyDaemon();
   if(dt.isDaemon())
     System.out.println("dt is a daemon thread.");
   Thread.sleep(10000);
   System.out.println("\nMain thread ending.");
 }

}</source>





A live daemon thread does not prevent an application from exiting.

   <source lang="java">

class MyThread extends Thread {

 MyThread() {
   setDaemon(true);
 }
 public void run() {
   boolean isDaemon = isDaemon();
   System.out.println("isDaemon:" + isDaemon);
 }

} public class Main {

 public static void main(String[] argv) throws Exception {
   Thread thread = new MyThread();
   thread.setDaemon(true);
   thread.start();
 }

}</source>





An application exits when there are no non-daemon threads running.

   <source lang="java">

class MyThread extends Thread {

 MyThread() {
   setDaemon(true);
 }
 public void run() {
   boolean isDaemon = isDaemon();
   System.out.println("isDaemon:" + isDaemon);
 }

} public class Main {

 public static void main(String[] argv) throws Exception {
   Thread thread = new MyThread();
   thread.setDaemon(true);
   thread.start();
 }

}</source>





A thread must be marked as a daemon thread before it is started.

   <source lang="java">

class MyThread extends Thread {

 MyThread() {
   setDaemon(true);
 }
 public void run() {
   boolean isDaemon = isDaemon();
   System.out.println("isDaemon:" + isDaemon);
 }

} public class Main {

 public static void main(String[] argv) throws Exception {
   Thread thread = new MyThread();
   thread.setDaemon(true);
   thread.start();
 }

}</source>





Daemon and User Threads

  1. A daemon thread is a background thread.
  2. It is subordinate to the thread that creates it.
  3. When the thread that created the daemon thread ends, the daemon thread dies with it.