2020-04-15

Java Daemon Thread

Java Daemon Thread


A daemon thread is a thread that plays a secondary role in helping other normal threads work.

Check if the boolean isDeaemon () thread is a daemon thread

void setDaemon (boolean on) Changes the thread to a daemon thread or a user thread.

Autosave thread programming

package javas;
import javax.swing.JOptionPane;
public class Thread1 {
 static boolean autoSave = false;
 public static void main(String args[]) {
  Runnable r = new Thread_1();
  Thread t1 = new Thread(r);
  t1.setDaemon(true);
  t1.start();
  for (int i = 0; i <= 20; i++) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
   }
   System.out.println(i);
   if (i == 5)
    autoSave = true;
  }
 }
}
class Thread_1 implements Runnable {
 public void run() {
  while (true) {
   try {
    Thread.sleep(5 * 1000);
   } catch (InterruptedException e) {
   }
   if (Thread1.autoSave) {
    autosave();
   }
  }
 }
 public void autosave() {
  System.out.println ("The work file has been saved automatically.");
 }
}

caution

The daemon process must be setDaemon before the process starts
Otherwise, IllegalThreadStateException is issued.

No comments:

Post a Comment