如何在 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 中临时挂起一个线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

掘金者说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值