如何保證只有一個線程在運行,在啓動線程的時候中止以前的線程?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