Java multithreading - thread abortion

Posted by The_broken on Sun, 06 Oct 2019 04:15:50 +0200

Incorrect thread abort - Stop

Stop: Discontinues threads and clears information about monitor locks, but may cause
JDK is not recommended for thread security issues.
Destroy: JDK does not implement this method.

/**
 * @author simon
 */
public class StopThread extends Thread {
    private int i = 0, j = 0;
    @Override
    public void run() {
        synchronized (this) {
            // Adding Synchronization Locks to Ensure Thread Safety
            ++i;
            try {
                // Sleep for 10 seconds, simulate time-consuming operation
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ++j;
        }
    }
    /** * Print i and j */
    public void print() {
        System.out.println("i=" + i + " j=" + j);
    }
}
/**
 * @author simon
 * Example 3 - Thread stop forcibly aborts, destroying thread security
 */
public class Demo {
    public static void main(String[] args) throws InterruptedException {
        StopThread thread = new StopThread();
        thread.start();
        // Hibernate for 1 second to ensure the success of i variable self-increment
        Thread.sleep(1000);
        // Pause thread
        thread.stop(); // Error termination
        //thread.interrupt(); // @ terminates correctly
        while (thread.isAlive()) {
            // Ensure that the thread has terminated
        } // Output result
        thread.print();
    }
}

Ideal state: either auto increment success i=1, j=1, or auto increment failure i=0, j=0
Real program execution results: i=1, j=0

There is no guarantee of data consistency in synchronization block, which destroys thread security.
stop method stops threads directly

Correct thread abort-interrupt

If the target thread is blocked when calling wait(), wait(long) or wait(long, int) methods, join(), join(long, int) or sleep(long, int) methods of the Object class, the Interrupt will take effect and the interrupt state of the thread will be cleared, throwing an InterruptedException exception.

If the target thread is blocked by Channel in I/O or NIO, similarly, I/O operations will be interrupted or special outliers returned. To terminate the thread.

If none of the above conditions are met, the interrupt state of the thread is set.

For the Demo example, stop() is changed to interrupt(), and the final output is "i=1 j=1" with the same data.

Correct thread abort-flag bit

/** Judgment by state position */
public class Demo4 extends Thread {
  public volatile static boolean flag = true;

  public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {
      try {
        while (flag) { // Judging whether to run or not
          System.out.println("Program in operation");
          Thread.sleep(1000L);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }).start();
    // After 3 seconds, change the status flag to False, which means no further running.
    Thread.sleep(3000L);
    flag = false;
    System.out.println("End of Program Running ____________");
  }
}

In the above code logic, add a judgment to control the termination of thread execution.

Topics: Java JDK Hibernate