Java 线程实现暂停、中止

2024-09-01 00:36
文章标签 java 实现 线程 中止 暂停

本文主要是介绍Java 线程实现暂停、中止,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求:用户可以开启任务,暂停任务和中止任务。
用户开启任务后,可以随时暂停或者中止。暂停后又可以回到原进度继续运行。

这里写目录标题

  • demo版-使用废弃的stop、suspend、resume实现
    • 为什么废弃了?原因是没有保证原子性
    • 不用stop,如何销毁线程呢?
  • 正式版
    • 延迟版:wait和notify、join和interrupt、LockSupport
    • 非延迟版:无法实现
  • 分布式集群最终版

demo版-使用废弃的stop、suspend、resume实现

一个MyTask类来实现线程,一个MyButton来模拟界面(最开始是想开线程监听控制台的,但是日志打印的频率不好控制,所以就出现了MyButton类)

package com.example.springbootproject.thread;import lombok.extern.slf4j.Slf4j;@Slf4j
public class MyTask extends Thread {@Overridepublic void run() {// 开启运行业务代码...processBusiness();}private void processBusiness() {/*** 模拟业务运行,不用sleep,因为会抛出打断异常;*/for (int i = 0; i < 1000000; i++) {log.info("business running...{}", i);for (int j = 0; j < 1000000; j++) {for (int k = 0; k < 100000; k++) {for (int l = 0; l < 100000; l++) {log.info("business running...l is" + l);for (int m = 0; m < 100000; m++) {for (int n = 0; n < 1000; n++) {int aa = i +j +k+m+n;int bb = aa *aa - m -n -i -j;for (int o = 0; o < aa; o++) {bb = aa+ bb;}}}}}}}}public void mySuspend() {this.suspend();log.info("suspend success");}public void myReStart() {this.resume();log.info("resume success");}public void myStop() {this.stop();log.info("stop success");}
}
package com.example.springbootproject.thread;import lombok.extern.slf4j.Slf4j;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;@Slf4j
public class MyButton {public static void main(String[] args) {// 创建一个 JFrame 窗口JFrame frame = new JFrame("My Button");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 创建一个 JPanel 面板JPanel panel = new JPanel();panel.setLayout(new FlowLayout());MyTask myTask = new MyTask();// 创建一个 JButton 按钮JButton startbutton = new JButton("start");startbutton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {myTask.start();log.info("start clicked!");}});final boolean[] flag = {false};// 创建一个 JButton 按钮JButton suspendbutton = new JButton("suspend");suspendbutton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (flag[0] == false) {myTask.mySuspend();flag[0] =true;} else {myTask.myReStart();flag[0] =false;}log.info("suspend clicked!");}});// 创建一个 JButton 按钮JButton stopButton = new JButton("stop");stopButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {log.info("stop clicked!");myTask.myStop();}});// 将按钮添加到面板panel.add(startbutton);panel.add(stopButton);panel.add(suspendbutton);// 将面板添加到窗口frame.getContentPane().add(panel);// 设置窗口的大小和可见性frame.setSize(300, 200);frame.setVisible(true);}
}

暂停后,输出是32,取消暂停后,又从33开始输出。最后停止线程
在这里插入图片描述

但是jdk自带的这三个方法已经废弃了,所以不用。

为什么废弃了?原因是没有保证原子性

但具体的代码还没有分析,先占个位置吧。TODO。

不用stop,如何销毁线程呢?

resume和suspend我们有很多函数可以代替。但是stop呢?
没有好办法。只能让线程里面的代码运行完,自己去关闭。
实际中都是用线程池去提交任务。那线程池的任务cancel可以吗?不可以。因为还是需要我们自己去控制当被打断时的逻辑
futureTask的cancel原码如下。传入一个布尔值,用来控制是否需要去打断当前任务。

  1. 首先进行cas操作,失败直接返回false;
  2. 如果设置了可打断,就去打断该任务
  3. 最后完成任务:里面的代码就是调用LockSupport.unpark打断线程
    所以如果我们没有处理该打断标志位或者没有处理好打断异常,代码还是会继续运行。
    在这里插入图片描述

正式版

正式版是用线程池去提交任务,和实际使用保持一致。

延迟版:wait和notify、join和interrupt、LockSupport

  • wait和notify原理: 这俩都是获得了monitor对象(synchronized锁对象)后才能使用。
    获得了obj的对象锁,当前线程调用obj.wait(),然后当前线程在其monitor对象上去等待,直到被打断(调用wait()前被打断,调用后被打断,都会抛出异常并清除打断标志)或者 其他线程调用了obj.notify或notifyall才可能会醒来。为啥可能呢?
    因为notify唤醒它之后,他还要竞争锁成功才能真正被唤醒,否则就进入阻塞状态。
  • join和interrupt: join,他不需要锁。当前线程调用了obj.join(),是当前线程 陷入阻塞。除非obj线程运行完成,或者线程被打断

我觉得无法实时去响应用户的操作,因为你如何让正在运行的 业务线程 去调用wait、join、LockSupport方法呢?
延迟版可以实现,可以对任务进行分步,每一步都可以用一个标志位去判断,如果为true,表示被暂停。
下面贴一个wait和notify版的,其他的join和locksupport也都可以实现,不再赘述

package com.example.springbootproject.thread;import lombok.extern.slf4j.Slf4j;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;@Slf4j
public class MyButton {public static void main(String[] args) {// 创建一个 JFrame 窗口JFrame frame = new JFrame("My Button");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 创建一个 JPanel 面板JPanel panel = new JPanel();panel.setLayout(new FlowLayout());ExecutorService executorService = Executors.newSingleThreadExecutor();final MyTask[] myTask = {null};// 创建一个 JButton 按钮JButton startbutton = new JButton("start");startbutton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {myTask[0] = new MyTask();executorService.submit(myTask[0]);log.info("start clicked!");}});final boolean[] flag = {false};// 创建一个 JButton 按钮JButton suspendbutton = new JButton("suspend");suspendbutton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (flag[0] == false) {myTask[0].mySuspend();flag[0] =true;} else {myTask[0].myReStart();flag[0] =false;}log.info("suspend clicked!");}});// 创建一个 JButton 按钮JButton stopButton = new JButton("stop");stopButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {log.info("stop clicked!");myTask[0].myStop();}});// 将按钮添加到面板panel.add(startbutton);panel.add(stopButton);panel.add(suspendbutton);// 将面板添加到窗口frame.getContentPane().add(panel);// 设置窗口的大小和可见性frame.setSize(300, 200);frame.setVisible(true);}
}
package com.example.springbootproject.thread;import lombok.extern.slf4j.Slf4j;@Slf4j
public class MyTask extends Thread{private Thread currentRunTask;@Overridepublic void run() {// 注意:this和Thread.currentThread不一样。因为我们使用线程池提交的任务// 前者是MyTask实例(state =new),后者是当前正在运行的线程(state=running)。// 而this就是MyTask实例代表的线程,它的状态是newcurrentRunTask = Thread.currentThread();// 开启运行业务代码...try {processBusiness();} catch (Exception e) {log.info("业务线程终止");}}private String processBusiness() throws InterruptedException {/*** 模拟业务运行,*/for (int i = 0; i < 1000000; i++) {log.info("business running...{}", i);for (int j = 0; j < 1000000; j++) {for (int k = 0; k < 100000; k++) {for (int l = 0; l < 100000; l++) {while (flag) { // 不用if。避免虚假唤醒synchronized (this) { // 获取try {log.info("业务线程 开始wait");this.wait();log.info("业务线程结束 wait");} catch (InterruptedException e) {log.info("处理业务过程中抛出一个异常");throw e;}}}log.info("business running...l is" + l);for (int m = 0; m < 100000; m++) {for (int n = 0; n < 10000; n++) {int aa = i + j + k + m + n;int bb = aa * aa - m - n - i - j;for (int o = 0; o < aa; o++) {bb = aa + bb;}}}}}}}return "0";}private boolean flag = false;public void mySuspend() {flag = true;log.info("suspend success");}public void myReStart() {synchronized (this) {flag = false;this.notifyAll();log.info("resume success");}}public void myStop() {currentRunTask.interrupt();flag = true;log.info("stop success");}
}

非延迟版:无法实现

分布式集群最终版

  1. 如何保证两次请求都打到同一个服务器上呢?
  2. 上下文切换也好消耗时间和内存
  3. 暂停多长时间合适呢?

所以,最终只能用数据库来保存才能达到要求。

这篇关于Java 线程实现暂停、中止的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125446

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap