如何保证只有一个线程在运行,在启动线程的时候中止以前的线程?html
实例以下:java
private volatile Thread udpSendThread;
线程:ide
class UdpSender extends Thread { @Override public void run() { if (udpSendThread == null) { return; } // other work } }
启动线程:spa
private void startUdpSender() { if (udpSendThread == null || !udpSendThread.isAlive()) { udpSendThread = new UdpSender(); udpSendThread.start(); } }
中止线程:线程
private void stopUdpSender() { Thread tmpThread = udpSendThread; udpSendThread = null; if (tmpThread != null) { tmpThread.interrupt(); } }
连接:http://forward.com.au/javaProgramming/HowToStopAThread.htmlcode