线程休眠

线程休眠

创建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 ends\n");
    }
}
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() {

    }
}

参考链接

上一篇:Java的线程介绍


下一篇:如何动态地从QLineEdit获取文本?