zoukankan      html  css  js  c++  java
  • Thread Tips

    1.把线程停掉方式

    Thread.stop() 使用这种方式是不安全的,官方也不建议,使用如下代码

    public abstract class StoppableRunnable implements Runnable {
        private volatile boolean stopWork;;
        private boolean done;
    
        public final void run() {
            setup();
            while(!stopWork && !done) {
                doUnitOfWork();
            }
            cleanup();
        }
    
        /**
         * Safely instructs this thread to stop working,
         * letting it finish it's current unit of work,
         * then doing any necessary cleanup and terminating
         * the thread.  Notice that this does not guarentee
         * the thread will stop, as doUnitOfWork() could
         * block if not properly implemented.
         */
        public void stop() {
            stopWork = true;
        }
    
        protected void done() {
            done = true;
        }
    
        protected void setup() { }
        protected void cleanup() { }
    
        /**
         * Does as small a unit of work as can be defined
         * for this thread.  Once there is no more work to
         * be done, done() should be called.
         */
        protected abstract void doUnitOfWork();
    }

    2.不要忽略中断异常

    public void foo() {
      try {Thread.sleep(1000);}
      catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }

    3.获取所有运行中线程

    public static String[] getThreadNames() {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup parent = null;
        while ( (parent = group.getParent()) != null ) {
          group = parent;
        }
        Thread[] threads = new Thread[group.activeCount()];
        group.enumerate(threads);
        java.util.HashSet set = new java.util.HashSet();
        for (int i=0; i < threads.length; ++i) {
          if (threads[i] != null && threads[i].isAlive()) {
            try {
              set.add(threads[i].getThreadGroup().getName()+","
                      +threads[i].getName()+","
                      +threads[i].getPriority());
            } catch (Throwable e) {e.printStackTrace();}
          }
        }
        String[] result = (String[]) set.toArray(new String[0]);
        java.util.Arrays.sort(result);
        return result;
      }

    参考

    http://www.billharlan.com/pub/papers/javatips.html

  • 相关阅读:
    linux下svn自动启动
    linux下SVN从一台服务器迁移到另一台服务器
    linux下安装subvision
    Activiti 6.0 变化
    Nexus3将本地jar包添加到仓库
    2021年放假安排
    字典词典工具
    测试问题及心得(实时修改添加)
    外网主机远程连接内网主机
    自动化测试
  • 原文地址:https://www.cnblogs.com/xiongmaotailang/p/5407212.html
Copyright © 2011-2022 走看看