线程关闭钩子 addShutdownHook

来源:互联网 发布:网络理财 网金社 编辑:程序博客网 时间:2024/05/18 14:15

----------------------------------------------main------------------------------------------------

1.把需要管理的线程放到List容器进行管理

2.把需要管理的线程放到线程组(ThreadGroup)中进行管理

import java.util.ArrayList;
import java.util.List;

public class RunTimeTest
{
    /**
     * 进程退出标识。进程被kill或ctrl+C 后此标识会被设置为true
     * */
    private static boolean processKilled = false;

    private static List<Thread> list = new ArrayList<Thread>();

    public static void main(String[] args)
    {
        // List<ExceptionMonitorVO> exList = new
        // ArrayList<ExceptionMonitorVO>();
        // final ThreadGroup channel = new ThreadGroup("task Group");

        Thread thread1 = new Thread(new RunnableImp());
        // Thread thread1 = new Thread(channel, new RunnableImp());

        thread1.setName("wo shi 1");
        thread1.start();
        list.add(thread1);

        Thread thread2 = new Thread(new RunnableImp());
        // Thread thread2 = new Thread(channel, new RunnableImp());

        thread2.setName("wo shi 2");
        thread2.start();
        list.add(thread2);

        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                processKilled = true;
                System.out.println("processKilled:" + processKilled);
                // Thread[] allThread = new Thread[channel.activeCount()];
                // channel.enumerate(allThread);
                System.out
                        .println("a kill signal detected, starting to quit...");
                System.out.println("the size of thread is: " + list.size());
                for (int i = 0, n = list.size(); i < n; i++)
                {

                    Thread t = list.get(i);
                    if (list.get(i) == null)
                    {
                        continue;
                    }
                    // 线程如果在sleep中,说明当前空闲,直接结束即可
                    if (Thread.State.TIMED_WAITING == t.getState())
                    {
                        System.out
                                .println((i + 1)
                                        + "/"
                                        + n
                                        + ":sleeping thread was interrupted,threadName=["
                                        + t.getName() + "]");
                        continue;
                    }
                    try
                    {
                        // 等待线程完成当前事务后再退出
                        System.out.println((i + 1) + "/" + n
                                + ":waiting thread to complete,threadName=["
                                + t.getName() + "]");
                        t.join();
                    }
                    catch (InterruptedException e)
                    {
                        System.out.println("thread name: " + t.getName());
                    }
                }
            }
        });
        try
        {
            thread1.join();
            thread2.join();
        }
        catch (InterruptedException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

    public static boolean isProcessKilled()
    {
        return processKilled;
    }

}

------------------------------------------------------------------------------------------------------

--------------------------------------------自定义线程-------------------------------------------

package com.test.hook;

public class RunnableImp implements Runnable
{

    @Override
    public void run()
    {
        try
        {
            Thread.sleep(5000);
            System.out.println("thread1...");
            int count = 0;
            while (true)
            {
                if (RunTimeTest.isProcessKilled())
                {
                    System.out.println("process is killed..");
                    break;
                }
                System.out.println(Thread.currentThread().getName()
                        + "******************count:" + count
                        + ",isProcessKilled:" + RunTimeTest.isProcessKilled());
                count++;
                for (int i = 0; i < 1000; i++)
                {
                    System.out.println(Thread.currentThread().getName()
                            + " num:" + i);
                }

            }
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

0 0