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");
- }