线程休眠
作者:互联网
线程休眠
创建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() {
}
}
参考链接
标签:sleepTime,System,休眠,线程,public,TestThread,out 来源: https://www.cnblogs.com/beyondx/p/15515928.html