• 驻守后台:守护线程


    package 第二章.守护线程;

    /**
    * Created by zzq on 2018/1/18.
    */
    public class 守护线程Test {
    public static class MyThread extends Thread{
    private int i = 0;
    @Override
    public void run(){
    super.run();
    try{
    while(true){
    i++;
    System.out.println("i="+i);
    Thread.sleep(1000);
    }
    }catch(InterruptedException ie){
    ie.printStackTrace();
    }
    }
    }
    public static class testThread extends Thread{
    @Override
    public void run(){
    try{
    Thread.sleep(10000); //testThread线程约10秒后结束
    System.out.println(Thread.currentThread().getName()+"线程结束!");
    }catch(InterruptedException ie){
    ie.printStackTrace();
    }
    }
    }
    public static class T1 extends Thread{
    @Override
    public void run() {
    for (int i = 0; i < 10; i++) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println(i);
    }
    }
    }

    public static void main(String[] args) throws InterruptedException {
    try{
    MyThread thread = new MyThread();
    thread.setName("thread");
    thread.setDaemon(true); //将thread线程设为守护线程
    thread.start();
    testThread t = new testThread();
    t.setName("testThread");
    t.start();
    //t.stop();//已经过期
    Thread.sleep(5000);//main线程在这里停留5秒
    System.out.println("主线程结束了");//5秒后main线程结束了,但是testThread线程还在执行,所以守护线程继续工作

    /*当所有线程都结束时,thread线程也随之结束*/
    }catch(InterruptedException ie){
    ie.printStackTrace();
    }
    /*守护线程 必须在start()方法之前 不然会报错,告诉你设置守护线程失败
    public final void setDaemon(boolean on) {
    checkAccess();
    if (isAlive()) {
    throw new IllegalThreadStateException();
    }
    daemon = on;
    }
    源码中说明 如果线程的运行状态是true 会抛异常
    */
    }
    }
  • 相关阅读:
    HDU 树型dp
    NOIP模拟 Math
    HTML5本地存储LocalStorage和sessionStorage
    数据结构与算法第一章答案
    堆和队列的应用之——简单计算器
    HITCS-LAB1 Linux 下C工具的应用
    cs:app 第二章homework(已完结)
    vim使用小结(1)
    学术英语写作(1)
    linux基础(2)
  • 原文地址:https://www.cnblogs.com/shizhijie/p/8431928.html
Copyright © 2020-2023  润新知