线程休眠

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了线程休眠脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

线程休眠

创建3个新线程, 每个线程随眠一段时间(0~6秒), 然后结束

public class ThreadSleepTester {
    public static void main(String[] args) {
        // 创建并命名每个线程
        TestThread thread1 = new TestThread("thread1");
        TestThread thread2 = new TestThread("thread2");
        TestThread thread3 = new TestThread("thread3");
        System.out.println("Starting threads");
        
        thread1.start();
        thread2.start();
        thread3.start();
        System.out.println("Thread started, main endsn");
    }
}
class TestThread extends Thread {
    
    private int sleepTime; // 休眠时间
    public TestThread(String name) {
        
        super(name);
        sleepTime(int) (Math.random() * 6000); // Math.random()产生随机数
    }
    
    public void run() {
        try {
            System.out.println(getName() + "going to sleep for " + sleepTime);
            Thread.sleep(sleepTime);
        } catch (InterruptedException exception) {
            
        }
        
        System.out.println(getName() + "finished");
    }
}
class TestThread implements Runnable {
    private int sleepTime;
    public TestThread() {

    }
}

参考链接

脚本宝典总结

以上是脚本宝典为你收集整理的线程休眠全部内容,希望文章能够帮你解决线程休眠所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: