栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何在 Java 中临时挂起一个线程?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在 Java 中临时挂起一个线程?

java中的线程是可以由用户创建的轻量级子进程。它用于在后台执行复杂的任务而不干扰主程序。为了暂时挂起线程,使其从运行状态进入等待状态。用于实现目标的概念是suspend() 函数。

方法:如何暂时挂起线程
  • 创建“ MyThread 类”,它扩展了“ java.lang.Thread 类”。它有一个run()函数,其中包含一些要执行的代码。
  • 在主函数中,使用setName()函数创建了一个名为“GFG”的“线程”对象“ MyThread 类” 。
  • 通过调用start()函数启动线程以执行其任务,并开始执行 run() 函数中编写的代码。

有时出于某些原因迫切需要暂停这些线程。所以这里程序展示了如何使用suspend()函数暂时挂起线程。线程将从运行状态进入等待状态。该函数使线程暂时停止执行。线程将保持等待 状态,直到我们恢复它。所以,在这个程序中,线程保持挂起直到睡眠时间,即 5 秒(在这个程序中采用)结束,然后我们使用 resume() 函数恢复它。

语法:为了获取当前线程的ID号已经创建

Thread.currentThread().getId();
使用的方法
  1. start():这是一种启动线程功能的方法。
  2. setName():这是一种用于设置创建的线程名称的方法。
  3. sleep(time):这是一种用于使线程休眠几毫秒时间的方法。
  4. suspend():这是一种用于挂起线程的方法。线程将保持挂起状态,并且在恢复之前不会执行其任务。
  5. resume():这是一种用于恢复挂起线程的方法。
例子
// Java program to suspend a thread temporarily
 
// Importing all classes from
// java.util package
import java.util.*;
 
// Class- MyThread
class MyThread extends Thread {
 
    // Remember : Method can be executed multiple times
    public void run()
    {
 
        // Try block to check if any exception occurs
        try {
 
            // Print and display the running thread
            // using currentThread() method
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
 
            // Message to be printed if
            // the exception is encountered
            System.out.println("Exception is caught");
        }
    }
}
 
// Class-Main
public class GFG {
 
    // Main Driver Method
    public static void main(String[] args) throws Exception
    {
 
        // Creating a thread
        MyThread thread = new MyThread();
 
        // Naming thread as "GFG"
        thread.setName("GFG");
 
        // Start the functioning of a thread
        thread.start();
 
        // Sleeping thread for specific amount of time
        Thread.sleep(500);
 
        // Thread GFG suspended temporarily
        thread.suspend();
 
        // Display message
        System.out.println(
            "Thread going to sleep for 5 seconds");
 
        // Sleeping thread for specific amount of time
        Thread.sleep(5000);
 
        // Display message
        System.out.println("Thread Resumed");
 
        // Thread GFG resumed
        thread.resume();
    }
}

输出

线程 13 正在运行
线程暂停
线程休眠 5 秒
线程恢复
参考

Java 中临时挂起一个线程

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020749.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号