java守护线程的定义:
? ? ?1.所谓守护线程就是运行在程序后台的线程,程序的主线程Main(比方java程序一开始启动时创建的那个线程)不会是守护线程.
?
? ? ? 2.Daemon thread在Java里面的定义是,如果虚拟机中只有Daemon thread 在运行,则虚拟机退出。?虚拟机中可能会同时有很多个线程在运行,只有当所有的非守护线程都结束的时候,虚拟机的进程才会结束,不管在运行的线程是不是main()线程。
?
? ? ? 3.Main主线程结束了(Non-daemon thread),如果此时正在运行的其他threads是daemon threads,JVM会使得这个threads停止,JVM也停下.如果此时正在运行的其他threads有Non-daemon threads,那么必须等所有的Non daemon线程结束了,JVM才会停下来.
?
? ? ? ?4.总之,必须等所有的Non-daemon线程都运行结束了,只剩下daemon的时候,JVM才会停下来,注意Main主程序是Non-daemon线程.
?
守护线程实例:
class="java" name="code">package cn.com.brilliance.atmv.udp; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.apache.log4j.Logger; public class UDPServer extends UDPObject { public static int MAX_RECEIVE = 1024; private static Logger logger = Logger.getLogger(UDPServer.class); private DatagramSocket ds = null; private boolean runFlag = false; private Thread t = null; private boolean isLogin = false; /** * default serve port */ private int port = 10001; public UDPServer(int port) { super(); this.port = port; } protected UDPServer() { super(); } class ServerThread implements Runnable { DatagramSocket ds = null; UDPService service = null; ServerThread(DatagramSocket ds, UDPService service) { this.ds = ds; this.service = service; } public void run() { byte buffer[] = new byte[MAX_RECEIVE]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length); logger.info("服务线程开始运行"); for(;;) { try { ds.receive(dp); if(dp.getLength() > 0) { System.out.println("rece data len:" + dp.getLength()); String rev = new String(buffer, 0, dp.getLength()); System.out.println("rev is:" + rev); String fromIP = dp.getAddress().getHostAddress(); logger.debug("收到报文[" +fromIP + ":" + dp.getPort() + "]: " + rev); if("#9999#".equals(rev)) { logger.info("收到退出指令,线程退出运行"); break; } try { service.process(buffer, dp.getLength(), fromIP, dp.getPort()); } catch(Exception e) { logger.error("process error:", e); } } } catch (Exception e) { throw new RuntimeException("", e); } } buffer = null; dp = null; } } public void listen(UDPService service) throws UDPException { if(!runFlag) { try { ds = new DatagramSocket(port); t = new Thread(new ServerThread(ds, service)); /* * 程序从main方法进入,如果将t设置为守护线程 这无法执行 */ //t.setDaemon(true); t.start(); runFlag = true; } catch (Exception e) { throw new UDPException("创建UDP失败.", e); } } else { //do nothing } } }
?
?