线程安全启动和停止
如何保证只有一个线程在运行,在启动线程的时候停止之前的线程?
实例如下:
private volatile Thread udpSendThread;
线程:
class UdpSender extends Thread { @Override public void run() { if (udpSendThread == null) { return; } // other work } }
启动线程:
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.html