YChalk

Daemon Thread

Mar 3rd, 2021 (edited)
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. public class Solution {
  2.     public static void main(String[] args) throws InterruptedException {
  3.         Thread target = new Thread();
  4.         LoggingStateThread loggingStateThread = new LoggingStateThread(target);
  5.  
  6.         loggingStateThread.start(); // NEW
  7.         Thread.sleep(100);
  8.         target.start();  // RUNNABLE
  9.         Thread.sleep(100);
  10.         // TERMINATED
  11.     }
  12. }
  13.  
  14. public class LoggingStateThread extends Thread{
  15.  
  16.     Thread thread;
  17.  
  18.     LoggingStateThread(Thread thread){
  19.         this.thread = thread;
  20.         this.setDaemon(true);
  21.     }
  22.  
  23.     @Override
  24.     public void run() {
  25.         System.out.println(thread.getState());
  26.         Thread.State pastState = thread.getState();
  27.         super.run();
  28.         while (!thread.getState().equals(State.TERMINATED)){
  29.                 State state = thread.getState();
  30.             if (!state.equals(pastState)){
  31.                 System.out.println(state);
  32.                 pastState = state;
  33.             }
  34.         }
  35.         System.out.println(thread.getState());
  36.     }
  37. }
  38.  
Add Comment
Please, Sign In to add comment