zoukankan      html  css  js  c++  java
  • Java并发编程(三)后台线程(Daemon Thread)

    后台线程,守护线程(Daemon Thread)

      所谓的后台线程,就是指这种线程并不属于程序中不可或缺的部分,因此当所有的非后台线程结束时,程序也就终止了,同时会杀死进程中的所有后台线程。通过setDaemon(true)来设置该线程为后台线程。

    package com.csdhsm.concurrent;
    
    import java.util.concurrent.TimeUnit;
    
    /** 
     * @Title: SimpleDaemonThreadDemo.java
     * @Package: com.csdhsm.concurrent
     * @Description to test the Daemon Thread
     * @author Han
     * @date 2016-4-19 下午3:56:51 
     * @version V1.0
     */ 
          
    public class SimpleDaemonThreadDemo implements Runnable{
    
        @Override
        public void run() {
            
            while(true){
                
                System.out.println(Thread.currentThread());
                try {
                    
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    
                    System.out.println("sleep is intrrupted!");
                }
            }
        }
        
        public static void main(String[] args) {
            
            for(int i = 0; i < 10; i++){
                
                Thread t = new Thread(new SimpleDaemonThreadDemo());
                //set the thread to daemon
                t.setDaemon(true);
                t.start();
            }
            
            try {
                //wait other thread to run
                TimeUnit.MILLISECONDS.sleep(30);
            } catch (InterruptedException e) {
                
            }
            
            System.out.println("Main thread is over");
        }
    }

    结果

      可以很清楚的看见当主线程结束之后,其他线程就没有再运行了。

  • 相关阅读:
    IOS开发——01_第一个OC程序
    01_iOS开发需要准备什么?
    正则表达式随笔
    .net4.6版本前设置window子窗口位置主窗口闪烁
    [CF1486D] Max Median
    [CF1487D] Pythagorean Triples
    [CF1487E] Cheap Dinner
    [CF1490E] Accidental Victory
    [CF1490F] Equalize the Array
    [CF1490G] Old Floppy Drive
  • 原文地址:https://www.cnblogs.com/a294098789/p/5408593.html
Copyright © 2011-2022 走看看