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; }
参考