Class KThread

java.lang.Object
java.lang.Thread
ch.k43.util.KThread
All Implemented Interfaces:
Runnable
Direct Known Subclasses:
KLogSMTPHandlerThread

public abstract class KThread extends Thread
This class adds some convenient methods for starting and stopping Java threads.
  Example: Start/stop thread
  
  // Create thread and call kStart() method
  KThread thread = new TestThread();
  ...
  
  // Signal termination and send interrupt to thread 
  thread.kStop();
  
  Example: User thread
  public class TestThread extends KThread {
  
        public TestThread() {
                        ...
        }
  
        public void kStart() {
                        ...
                        // Run until kStop() is called 
                        while (!kMustTerminate()) {
                        ...
                        }
        }
  
        public synchronized void kCleanup() {
                        // Do any resource cleanup (will be called automatically)
        }
  }
  
Since:
2024.09.06
  • Method Details

    • kCleanup

      public void kCleanup()
      Cleanup method called by run() just before termination.
    • kMustTerminate

      public final boolean kMustTerminate()
      Check if thread should be terminated.
      Returns:
      True (if kStop() was called previously), false otherwise
      See Also:
    • kStart

      public abstract void kStart()
      Main entry point for user thread. This method must be implemented by the subclass.
    • kStop

      public final void kStop()
      Set the thread termination flag and interrupt the thread.
    • kStop

      public final void kStop(boolean argInterrupt)
      Set the thread termination flag and optionally send interrupt to the thread.
      Parameters:
      argInterrupt - Send interrupt signal to thread
    • run

      public final void run()
      Start thread by calling method kStart(). After kStart() returns, the method kCleanup() is automatically called to allow for any resource cleanup by the user thread.
      Specified by:
      run in interface Runnable
      Overrides:
      run in class Thread
    • start

      public final void start()
      Prohibit overwriting.
      Overrides:
      start in class Thread
    • toString

      public String toString()
      Output object data.
      Overrides:
      toString in class Thread