|
| 1 | +package org.javacore.thread; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutorService; |
| 4 | +import java.util.concurrent.Executors; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | + |
| 7 | +/** |
| 8 | + * Created by BYSocket on 2015/11/2. |
| 9 | + * |
| 10 | + * Copyright [2015] [Jeff Lee] |
| 11 | + * |
| 12 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 13 | + * you may not use this file except in compliance with the License. |
| 14 | + * You may obtain a copy of the License at |
| 15 | + * |
| 16 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 17 | + * |
| 18 | + * Unless required by applicable law or agreed to in writing, software |
| 19 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 20 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 21 | + * See the License for the specific language governing permissions and |
| 22 | + * limitations under the License. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @author Jeff Lee |
| 27 | + * @since 2015-11-3 09:04:16 |
| 28 | + * 休眠线程sleep的使用 |
| 29 | + */ |
| 30 | +public class SleepingTask extends LiftOff { |
| 31 | + @Override |
| 32 | + public void run(){ |
| 33 | + while(countDown-- > 0){ |
| 34 | + try { |
| 35 | + System.out.println(status()); |
| 36 | + // 老版本调用:Thread.sleep(1000); |
| 37 | + TimeUnit.MICROSECONDS.sleep(100); |
| 38 | + } catch (InterruptedException e) { |
| 39 | + e.printStackTrace(); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + // 创建新的线程池 |
| 46 | + ExecutorService exec = Executors.newCachedThreadPool(); |
| 47 | + for (int i = 0; i < 5;i++) |
| 48 | + exec.execute(new SleepingTask());// 由线程池决定执行线程 |
| 49 | + // 顺序关闭,执行以前提交的线程,不接受新的线程 |
| 50 | + exec.shutdown(); |
| 51 | + } |
| 52 | +} |
0 commit comments