High-performance programming - multi-threaded Java Programming Fundamentals of thread abort

Incorrect thread abort

Stop method

Suspend threads, and clear information monitor locks, but may lead to thread-safety issues, JDK is not recommended

Destroy

JDK does not implement this method

The sample code

? Why not recommend the use of a piece of code stop it will be able to answer:

package com.study.hc.thread.chapter1.thread;
public class StopThread extends Thread {
  private int i = 0, j = 0;

  @Override
  public void run() {
    synchronized (this) {
	    // 增加同步锁,确保线程安全
	    ++i;
	    try {
	      // 休眠10秒,模拟耗时操作
	      Thread.sleep(10000);
	    } catch (InterruptedException e) {
	      e.printStackTrace();
	    }
	    ++j;
    }
  }

  /** * 打印i和j */
  public void print() {
  System.out.println("i=" + i + " j=" + j);
  }
}

Execute the code:

package com.study.hc.thread;

public class Demo3 {

    public static void main(String[] args) throws InterruptedException {
        StopThread thread = new StopThread();
        thread.start();//启动线程
        Thread.sleep(1000);//主线程休眠1s,保证子线程的执行
        thread.stop();//错误的中止
        while(thread.isAlive()){
            //确保线程已中止
        }
        //输出结果
        thread.print();
    }
}

problem analysis

Output:

i=1 j=0

Obviously the answer is not conformant, the main problem when it is in the implementation of the completion ++ i did not wait thread.sleep (10000) suspended on the end of the thread, so ++ i ++ j performed and did not carried out. So it would destroy the data consistency and atomicity code

Proper termination

Or the above code, simply do the appropriate corrections.

package com.study.hc.thread;

public class Demo3 {

    public static void main(String[] args) throws InterruptedException {
        StopThread thread = new StopThread();
        thread.start();//启动线程
        Thread.sleep(1000);//主线程休眠1s,保证子线程的执行
        //thread.stop();//错误的中止
        thread.interrupt();//正确的终止
        while(thread.isAlive()){
            //确保线程已中止
        }
        //输出结果
        thread.print();
    }
}

interrupt

If the target of the call to wait Object (), wait (long, int), is blocked when the join (), join (long, int) or sleep (long, ing) and other methods, then the interrupt will take effect, interrupting the thread status is cleared, throw InterruptedException exception.

If the goal is blocked by I / O or the NIO Channel, likewise, I / O operation may be interrupted or abnormal return values. The purpose of the suspension thread.

If the above status are not met, it will set the thread's interrupt status

To achieve control of the suspension by the flag

package com.study.hc.thread;


public class Demo4 {

    public volatile static boolean flag = true;

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
               try {
                   while (flag){
                       System.out.println("运行中");
                       Thread.sleep(1000L);
                   }
               }catch (InterruptedException e) {
                    e.printStackTrace();
               }
        }).start();
        //3秒之后,将状态标志该为false,代表不继续运行。
        Thread.sleep(3000L);
        flag=false;
        System.out.println("程序运行结束");
    }
}

In the snippet, joined the flag this flag, when it is time to true, let the program running, and when it is time false, then realized aborted.

Published 37 original articles · won praise 10 · views 727

Guess you like

Origin blog.csdn.net/weixin_41746577/article/details/103772603