使用TimeUnit来休眠
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- public class SleepingLiftOff implements Runnable{
- protected int countDown = 10;
-
- private static int count = 0;
-
- private final int id = count++;
-
- SleepingLiftOff(int countDown){
- this.countDown = countDown;
- }
-
- public String Status(){
- return "T" + id + "[" + (countDown > 0 ? countDown : "LiftOff") + "] ";
- }
-
- @Override
- public void run() {
- //直接捕获异常,因为异常不能跨线程传播
- try {
-
- while(countDown-- > 0){
- //打印倒计时
- System.out.print(Status());
-
- //老的休眠写法
- //Thread.sleep(3000);
-
- //新的休眠写法
- TimeUnit.MILLISECONDS.sleep(3000);
- }
-
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- public static void main(String[] args) {
- ExecutorService exec = Executors.newCachedThreadPool();
-
- for (int i = 0; i < 3; i++) {
- exec.execute(new SleepingLiftOff(5));
- }
-
- exec.shutdown();
- }
- }
复制代码
|
|