zoukankan      html  css  js  c++  java
  • 2.5 驻守后台:守护线程

    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 会抛异常
    */
    }
    }
  • 相关阅读:
    处在什么都想学,却又不知道怎么学的处境
    启动MongoDB shell客户端会什么会一闪而过
    Socket.io发送消息含义
    轮询、长轮询与Web Socket的前端实现
    org.apache.commons.lang3.StringUtils类中isBlank和isEmpty方法的区别
    JS学习笔记10_Ajax
    JS学习笔记9_JSON
    JS学习笔记8_错误处理
    JS学习笔记7_表单脚本
    JS学习笔记6_事件
  • 原文地址:https://www.cnblogs.com/anxbb/p/8425435.html
Copyright © 2011-2022 走看看