多线程编程<四>
1 /** 2 * 守护线程daemon['diːmən] 3 * @author Administrator 4 * 5 */ 6 public class DaemonDemo { 7 public static void main(String[] args) { 8 MyDaemon dt = new MyDaemon(); 9 10 if (dt.thrd.isDaemon()) { 11 System.out.println("dt is a daemon thread."); 12 } 13 System.out.println("Sleeping in main thread."); 14 try{ 15 Thread.sleep(10000); 16 } 17 catch(InterruptedException exc){ 18 System.out.println("Main thread interrupted."); 19 } 20 21 System.out.println("\nMain thread ending."); 22 } 23 } 24 25 class MyDaemon implements Runnable{ 26 Thread thrd; 27 28 public MyDaemon() { 29 thrd = new Thread(this); 30 thrd.setDaemon(true);//守护线程:当用户线程结束时,守护线程也结束。 31 thrd.start(); 32 } 33 34 @Override 35 public void run() { 36 37 try { 38 for(;;) { 39 System.out.print("."); 40 Thread.sleep(1000); 41 } 42 } catch (InterruptedException e) { 43 System.out.println("MyDaemon interrupted."); 44 } 45 } 46 }
一个简单的Reminder
1 import java.util.Calendar; 2 import java.util.GregorianCalendar; 3 4 5 public class ReminderDemo { 6 public static void main(String[] args) { 7 Reminder mt = new Reminder("Call Harry", 2); 8 9 Reminder mt2 = new Reminder("Meet with Bill", new GregorianCalendar(2014,4,14,21,14)); 10 11 for(int i = 0; i < 20; i++){ 12 try { 13 Thread.sleep(1000); 14 } catch (InterruptedException e) { 15 System.out.println("Main thread interrupted."); 16 } 17 System.out.print("."); 18 } 19 System.out.println("\nMain thread ending."); 20 } 21 } 22 class Reminder implements Runnable { 23 24 Calendar reminderTime; 25 26 String message; 27 28 public Reminder(String msg, int delay) { 29 message = msg; 30 reminderTime = Calendar.getInstance(); 31 reminderTime.add(Calendar.SECOND, delay); 32 System.out.printf("Reminder set for %tD %1$tr\n", reminderTime); 33 Thread dThrd = new Thread(this); 34 dThrd.setDaemon(true); 35 dThrd.start(); 36 } 37 38 public Reminder(String msg, Calendar cal) { 39 message = msg; 40 41 reminderTime = cal; 42 System.out.printf("Reminder set for %tD %1$tr\n", reminderTime);//变元索引 43 Thread dThrd = new Thread(this); 44 dThrd.setDaemon(true); 45 dThrd.start(); 46 } 47 @Override 48 public void run() { 49 try { 50 for(;;){ 51 Calendar curTime = Calendar.getInstance(); 52 if(curTime.compareTo(reminderTime) >= 0) { 53 System.out.println("\n" + message + "\n"); 54 break; 55 } 56 Thread.sleep(1000); 57 } 58 } catch (InterruptedException e) { 59 System.out.println("Reminder interrupted."); 60 } 61 } 62 63 }