OneCoder(苦逼Coder)原创,转载请务必注明出处: http://www.coderli.com/archives/daemon-thread-plain-words/ web
关于“白话”:偶然想到的词,也许有一天能成为一个系列。目的就是用简洁,明快的语言来告诉您,我所知道的一切。ide
- Thread commonThread = new Thread("Common Thread");
这样就是用户线程。测试
- Thread daemonThread = new Thread("Daemon Thread");
- daemonThread.setDaemon(true);
这样就是守护线程。this
起了“守护”线程这么动听的名字,天然要起到“守护”的做用。就比如男人要守护妹子。spa
- /**
- * 测试两个用户线程的状况
- *
- * @author lihzh(OneCoder)
- * @date 2012-6-25 下午10:07:16
- */
- private static void twoCommonThread() {
- String girlOneName = "Girl One";
- Thread girlOne = new Thread(new MyRunner(3000, girlOneName), girlOneName);
- String girlTwoName = "Girl Two";
- Thread girlTwo = new Thread(new MyRunner(5000, girlTwoName), girlTwoName);
- girlOne.start();
- System.out.println(girlOneName + "is starting.");
- girlTwo.start();
- System.out.println(girlTwoName + "is starting");
- }
- private static class MyRunner implements Runnable {
- private long sleepPeriod;
- private String threadName;
- public MyRunner(long sleepPeriod, String threadName) {
- this.sleepPeriod = sleepPeriod;
- this.threadName = threadName;
- }
- @Override
- public void run() {
- try {
- Thread.sleep(sleepPeriod);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(threadName + " has finished.");
- }
- }
开始都活着。线程
3秒后,妹子1挂了,妹子2活的好好的,她的寿命是5秒。3d
- /**
- * 测试一个用户一个守护线程
- *
- * @author lihzh(OneCoder)
- * @date 2012-6-25 下午10:22:58
- */
- private static void oneCommonOneDaemonThread() {
- String girlName = "Girl";
- Thread girl = new Thread(new MyRunner(3000, girlName), girlName);
- String princeName = "Prince";
- Thread prince = new Thread(new MyRunner(5000, princeName), princeName);
- girl.start();
- System.out.println(girlName + "is starting.");
- prince.setDaemon(true);
- prince.start();
- System.out.println(prince + "is starting");
- }
开始快乐的生活着,妹子能活3秒,王子原本能活5秒。code
可是3秒后,妹子挂了,王子也殉情了。orm
你可能会问,若是王子活3秒,妹子能活5秒呢。我只能说,虽然你是王子,该挂也得挂,妹子还会找到其余高富帅的,懂?对象
看,王子已经挂了。
- /**
- * 测试两个守护线程
- *
- * @author lihzh(OneCoder)
- * @date 2012-6-25 下午10:29:18
- */
- private static void twoDaemonThread() {
- String princeOneName = "Prince One";
- Thread princeOne = new Thread(new MyRunner(5000, princeOneName), princeOneName);
- String princeTwoName = "Prince Two";
- Thread princeTwo = new Thread(new MyRunner(3000, princeTwoName), princeTwoName);
- princeOne.setDaemon(true);
- princeOne.start();
- System.out.println(princeOneName + "is starting.");
- princeTwo.setDaemon(true);
- princeTwo.start();
- System.out.println(princeTwoName + "is starting");
- }