1、后台线程的基本用法
XML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package com.lyzx.restdy.callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * 守护/后台线程 * 所谓的后台线程或者说守护线程要和非后台线程做比较 * 一般情况下当所有的非后台线程都结束(也就意味着整个应用程序结束) 后台线程也自动结束 * 后台线程一般情况下run方法里面放一些死循环 * 等待整个程序结束后自动结束 */ public class T2 { public static void main(String[] args) { usePool(); try { TimeUnit.MILLISECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 可以看到线程池的线程数和线程工程中打印的次数是一样的 * 说明线程池pool使用DaemonFactory这个线程池创建了2个线程用于执行任务 */ public static void usePool(){ ExecutorService pool = Executors.newFixedThreadPool(2,new DaemonFactory()); for(int i=0;i<10;i++){ Thread task = new Thread(new Daemon()); pool.submit(task); } pool.shutdown(); } public static void useFactory(){ DaemonFactory df = new DaemonFactory(); for(int i=0;i<10;i++){ Thread t = df.newThread(new Daemon()); t.start(); } } } class Daemon implements Runnable{ @Override public void run() { while(true){ System.out.println(Thread.currentThread().getName()+"在执行任务...."); } } } /** * 线程工厂 * 通过传入一个Runnable返回一个Thread * 使用这个工程类创建的线程直接就是守护线程 * 注意要设置后台线程必须在线程启动之前调用setDaemon() */ class DaemonFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); System.out.println(this.getClass().getSimpleName()+"创建了一个线程."); return t; } } |
XML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.lyzx.restdy.callable;
/** * 在后台线程中开启的线程依然是后台线程 */ public class T3 { public static void main(String[] args) { Thread t= new Thread(new V()); t.setDaemon(true); t.start(); try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class V implements Runnable{ Thread[] t = new Thread[10]; @Override public void run() { for(Thread item : t){ item=new Thread(new C()); System.out.println("===="+item.isDaemon()); } } } class C implements Runnable{ @Override public void run() { System.out.println("...."); } } |