|
| 1 | +package org.javacore.thread; |
| 2 | + |
| 3 | +import java.util.concurrent.TimeUnit; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by BYSocket on 2015/11/2. |
| 7 | + * |
| 8 | + * Copyright [2015] [Jeff Lee] |
| 9 | + * |
| 10 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 | + * you may not use this file except in compliance with the License. |
| 12 | + * You may obtain a copy of the License at |
| 13 | + * |
| 14 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | + * |
| 16 | + * Unless required by applicable law or agreed to in writing, software |
| 17 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 18 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | + * See the License for the specific language governing permissions and |
| 20 | + * limitations under the License. |
| 21 | + */ |
| 22 | +/** |
| 23 | + * @author Jeff Lee |
| 24 | + * @since 2015-11-3 18:09:06 |
| 25 | + * Daemon后台线程的简单使用 |
| 26 | + */ |
| 27 | +public class SimpleDaemons implements Runnable{ |
| 28 | + @Override |
| 29 | + public void run() { |
| 30 | + try { |
| 31 | + while (true){ |
| 32 | + TimeUnit.MICROSECONDS.sleep(1000); |
| 33 | + System.out.println(Thread.currentThread() + " " + this); |
| 34 | + } |
| 35 | + } catch (InterruptedException e) { |
| 36 | + System.out.println("sleep() interrupted"); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // main是非后台线程 |
| 41 | + public static void main(String[] args) throws InterruptedException { |
| 42 | + for (int i = 0 ; i < 10 ; i++){ |
| 43 | + // 创建一个新线程 |
| 44 | + Thread daemon = new Thread(new SimpleDaemons()); |
| 45 | + // 设置为后台线程 |
| 46 | + daemon.setDaemon(true); |
| 47 | + daemon.start(); |
| 48 | + } |
| 49 | + System.out.println("所有任务已启动"); |
| 50 | + // 如果main结束,那么同时会杀死所有后台线程,多次运行你会发现,可能打印的后台线程数不定 |
| 51 | + TimeUnit.MICROSECONDS.sleep(175); |
| 52 | + } |
| 53 | +} |
0 commit comments