溫馨提示×

java如何暫停另外一個線程

小億
107
2024-03-29 15:31:07
欄目: 編程語言

在Java中,可以通過使用Thread類的suspend()resume()方法來暫停和恢復(fù)線程的執(zhí)行。

以下是一個示例代碼,演示如何暫停一個線程:

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(); // 恢復(fù)線程
    }
    
    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();
                }
            }
        }
    }
}

在上面的示例中,我們創(chuàng)建了一個實現(xiàn)Runnable接口的內(nèi)部類MyRunnable,并在其中定義了一個無限循環(huán),在循環(huán)中輸出一條信息并休眠500毫秒。在main方法中,我們創(chuàng)建了一個線程t1并啟動它,然后在2秒后調(diào)用t1.suspend()方法暫停線程的執(zhí)行,再等待2秒后調(diào)用t1.resume()方法恢復(fù)線程的執(zhí)行。

需要注意的是,suspend()resume()方法在Java中已經(jīng)被標(biāo)記為過時方法,不推薦使用。更好的做法是使用wait()notify()方法或者LockCondition來實現(xiàn)線程的暫停和恢復(fù)。

0