java如何暂停另外一个线程

2024-04-20

在Java中,可以通过使用Thread类的suspend()resume()方法来暂停和恢复线程的执行。

以下是一个示例代码,演示如何暂停一个线程:

public class SuspendResumeThreadExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
        
        try {
            Thread.sleep(2000); // 等待2秒钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t1.suspend(); // 暂停线程
        
        try {
            Thread.sleep(2000); // 等待2秒钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        t1.resume(); // 恢复线程
    }
    
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            while (true) {
                System.out.println("Thread is running...");
                try {
                    Thread.sleep(500); // 休眠500毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在上面的示例中,我们创建了一个实现Runnable接口的内部类MyRunnable,并在其中定义了一个无限循环,在循环中输出一条信息并休眠500毫秒。在main方法中,我们创建了一个线程t1并启动它,然后在2秒后调用t1.suspend()方法暂停线程的执行,再等待2秒后调用t1.resume()方法恢复线程的执行。

需要注意的是,suspend()resume()方法在Java中已经被标记为过时方法,不推荐使用。更好的做法是使用wait()notify()方法或者LockCondition来实现线程的暂停和恢复。