[Java multithreading] stop the thread

Mu Xin 2021-11-25 18:30:53
java multithreading stop thread

Catalog

1. Methods to stop threads

2. Determine whether the thread is in the stopped state

3. Threads that can be stopped —— Anomaly method

4. Stop in a deep sleep

5. Threads that can be stopped —— The violence stopped

6. Method stop() And java,lang.ThreadDeath abnormal

7. Use return Stop thread


1. Methods to stop threads

stay Java There are the following 3 There are two ways to terminate an ongoing thread :

1) Use exit sign , Normal thread exit , That is to say run Thread termination after method completion .

2) Use stop Method to forcibly terminate a thread , But this method is not recommended , because stop and suspend And resume equally , It's all a way to expire , Using them can produce unexpected results .

3) Use interrupt Method interrupt thread .

Stopping a thread means stopping the operation before the thread finishes processing the task , That is to give up the current operation . Although it seems very simple , But precautions must be taken , In order to achieve the desired effect . Stop a thread to use Thread.stop() Method , but Better not use it . Although it does stop a running thread , But this method is not safe (unsafe), And it has been abandoned (deprecated), In the future Java In the version , This method will not be available or supported .

Most operations that stop a thread use Thread.interrupt() Method , Although the name of the method is “ stop it , suspend ” It means , But this method does not terminate a running thread , You also need to add a judgment to complete the thread stop .

2. Determine whether the thread is in the stopped state

Thread.java Class provides two methods .

1)this.interrupted(): Test whether the current thread has been interrupted .

Test whether the current thread is interrupted .  This method can clear the interrupt state of the thread , After execution, the status flag can be set to... And eliminated false The function of  .  let me put it another way , If this method is called twice in succession , Then the second call will return false( Unless the current thread is interrupted again , After the first call has cleared its interrupt state , It has been checked before the second call ).

Ignore thread interrupts , Because the thread does not exist when interrupted, it will be returned by this method false Reflected in .

// Source code , Statement
public void interrupt();

2)this.isInterrupted(): Test whether the thread has been interrupted .

Test whether the thread is interrupted .  The thread's interrupt state is not affected by this method , But do not clear status flags .

Ignore thread interrupts , Because the thread does not exist when interrupted, it will be returned by this method false Reflected in .

// Source code , Statement
public static boolean interrupted();
public boolean isInterrupted();

3. Threads that can be stopped —— Anomaly method

Here is an example :

Custom thread :

public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println(" It's stopped ! I'm quitting !");
break;
}
System.out.println("i=" + (i + 1));
}
System.out.println(" I was exported , If this code is for And keep running again , The thread did not stop !");
}
}

Run code :

public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

The example above stops the thread , But if for There are also statements below the statement , It will continue to run .

Change the above code to :

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 500000; i++) {
if (this.interrupted()) {
System.out.println(" It's stopped ! I'm quitting !");
throw new InterruptedException();
}
System.out.println("i=" + (i + 1));
}
System.out.println(" I am here for below ");
} catch (InterruptedException e) {
System.out.println(" Into the MyThread.java class run There are two ways catch 了 !");
e.printStackTrace();
}
}
}

Output results :

4. Stop in a deep sleep

If the thread is in sleep() Stop thread in state , What would be the effect ?

Here is an example to illustrate :

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println(" To be stopped in a deep sleep ! Get into catch!"+this.isInterrupted());
e.printStackTrace();
}
}
}

Run code :

public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(200);
thread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}

Execution results :

  From the print results , If in sleep Stop a thread in state , Will enter catch sentence , And clear the stop state value , Makes it false.

【 notes 】: If you stop the thread first , Then enter sleep, What will happen ? The following example :

public class MyThread extends Thread {
@Override
public void run() {
super.run();
try {
for(int i=0;i<100000;i++){
System.out.println("i="+(i+1));
}
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println(" First stop , I met again sleep! Get into catch!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
System.out.println("end!");
}
}

5. Threads that can be stopped —— The violence stopped

Use stop() Method to stop a thread is very violent .

public class MyThread extends Thread {
private int i = 0;
@Override
public void run() {
try {
while (true) {
i++;
System.out.println("i=" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(8000);
thread.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Running results :

6. Method stop() And java,lang.ThreadDeath abnormal

call stop() Method will throw java.lang.ThreadDeath abnormal , But under normal circumstances , This exception does not need to be captured explicitly .

Method stop() Has been voided , Because if you force the thread to stop, it may cause some cleaning work not to be completed . Another case is to lock the object ” Unlock “, Processing that results in data not being synchronized , There's a data inconsistency .

7. Use return Stop thread

The method interrupt() and return It can also achieve the effect of thread stopping .

public class MyThread extends Thread {
@Override
public void run() {
while (true) {
if (this.isInterrupted()) {
System.out.println(" Stopped. !");
return;
}
System.out.println("timer=" + System.currentTimeMillis());
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyThread t=new MyThread();
t.start();
Thread.sleep(1000);
t.interrupt();
}
}

Execution results :

  However, it is recommended to use " Throw exceptions " To achieve thread stop , Because in catch You can also throw exceptions up in the block , Events that cause threads to stop are propagated .

版权声明
本文为[Mu Xin]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109101849550S.html

  1. Java经典面试题详解,突围金九银十面试季(附详细答案,mysql集群架构部署方案
  2. java整理,java高级特性编程及实战第一章
  3. java教程——反射,mongodb下载教程
  4. Java岗大厂面试百日冲刺 - 日积月累,每日三题【Day12,zookeeper原理作用
  5. Java后端互联网500道中高级面试题(含答案),linux钩子技术
  6. java8 Stream API及常用方法,java初级程序员面试
  7. java-集合-Map(双列)——迪迦重制版,2021Java开发社招面试解答之性能优化
  8. Flink处理函数实战之二:ProcessFunction类,java线程面试题目
  9. flex 布局详解,【Java面试题
  10. Linux basic command learning
  11. Why did docker lose to kubernetes? Docker employee readme!
  12. MySQL安装
  13. Elastic Search Aggregate Learning five: Problem Analysis of Uncertainty of sequencing results, Alibaba Java Performance Tuning Practical
  14. Installing, configuring, starting and accessing rabbitmq under Linux
  15. Oracle SQL injection summary
  16. Installation MySQL
  17. L'exposition à la photo d'essai sur la route i7 du nouveau vaisseau amiral de BMW Pure Electric a également été comparée à celle de Xiaopeng p7.
  18. spring JTA 关于异常处理的时机问题
  19. Le problème du temps de traitement des exceptions dans la JTA printanière
  20. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  21. Oracle SQL injection summary
  22. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  23. Do you really know MySQL order by
  24. Record a java reference passing problem
  25. spring JTA 關於异常處理的時機問題
  26. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  27. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  28. Java 8 Stream API and common methods, Java Junior Program interview
  29. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  30. git(3)Git 分支,zookeeper下载教程
  31. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  32. Entretien d'entretien d'usine Java post sprint de 100 jours - accumulation de jours et de mois, trois questions par jour [jour 12, fonction de principe de Zookeeper
  33. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  34. How to analyze several common key and hot issues in redis from multiple dimensions
  35. GIT (3) GIT Branch, Zookeeper Download tutoriel
  36. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  37. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  38. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  39. Springboot has 44 application initiators
  40. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  41. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  42. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  43. GitHub上标星2,java项目开发实训教程
  44. Docker development environment Preview
  45. JavaScript高級深入淺出:掌握 this 指向
  46. JavaScript Advanced Insight and outside: Mastering this direction
  47. Vue de l'application pratique de Javascript, drop drag Event
  48. docker 安装部署 Jenkins 2.322
  49. kafka安装
  50. 近九万字图文详解RabbitMQ
  51. Engaged in Java for one and a half years, how to break through yourself
  52. 输出9*9乘法表----java
  53. 判断一个数是不是素数-------java
  54. java项目,记录页面修改值,内部打“官司”用
  55. Docker installation Deployment Jenkins 2.322
  56. Comment porter un pantalon en hiver? Les petits hommes, les jambes épaisses et la largeur de l'entrejambe peuvent être vus. 3 techniques pour éviter la foudre
  57. MySQL下载和安装教程
  58. In depth analysis of rocketmq source code - message storage module
  59. Spring transaction management
  60. mysql恢复ibd数据,为何频频报错?