java中的线程是可以由用户创建的轻量级子进程。它用于在后台执行复杂的任务而不干扰主程序。为了暂时挂起线程,使其从运行状态进入等待状态。用于实现目标的概念是suspend() 函数。
方法:如何暂时挂起线程
- 创建“ MyThread 类”,它扩展了“ java.lang.Thread 类”。它有一个run()函数,其中包含一些要执行的代码。
- 在主函数中,使用setName()函数创建了一个名为“GFG”的“线程”对象“ MyThread 类” 。
- 通过调用start()函数启动线程以执行其任务,并开始执行 run() 函数中编写的代码。
有时出于某些原因迫切需要暂停这些线程。所以这里程序展示了如何使用suspend()函数暂时挂起线程。线程将从运行状态进入等待状态。该函数使线程暂时停止执行。线程将保持等待 状态,直到我们恢复它。所以,在这个程序中,线程保持挂起直到睡眠时间,即 5 秒(在这个程序中采用)结束,然后我们使用 resume() 函数恢复它。
语法:为了获取当前线程的ID号已经创建
Thread.currentThread().getId();
使用的方法
- start():这是一种启动线程功能的方法。
- setName():这是一种用于设置创建的线程名称的方法。
- sleep(time):这是一种用于使线程休眠几毫秒时间的方法。
- suspend():这是一种用于挂起线程的方法。线程将保持挂起状态,并且在恢复之前不会执行其任务。
- 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 秒
线程恢复