Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 21st, 2012  |  syntax: None  |  size: 1.96 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Confusion on Thread setDeaemon in java
  2. public class DeamonSample implements Runnable
  3. {
  4.       public void run()
  5.       {
  6.             try
  7. {
  8. System.out.println("T1 started...");
  9.  
  10.                   for (int i=0;i<1000;i++)
  11.                   {
  12.                         TimeUnit.SECONDS.sleep(1);
  13.                         System.out.print(i+" ");
  14.                   }
  15.             }
  16.             catch (InterruptedException e)
  17.             {
  18.                   // TODO Auto-generated catch block
  19.                   e.printStackTrace();
  20.             }
  21.             finally
  22.             {
  23.                   System.out.println("T1 ended...");
  24.             }
  25.  
  26.       }
  27.  
  28.  
  29.       /**
  30.       * @param args
  31.       */
  32.       public static void main(String[] args)
  33.       {
  34.             // TODO Auto-generated method stub
  35.             System.out.println("Main Started...");
  36.             System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
  37.             DeamonSample deamonSample=new DeamonSample();
  38.             Thread t1=new Thread(deamonSample);
  39.             t1.setDaemon(true);
  40.             t1.start();
  41.             System.out.println("T1 Type="+t1.isDaemon());
  42.             System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
  43.             System.out.println("Main ended...");
  44.       }
  45.  
  46. }
  47.        
  48. import java.util.concurrent.atomic.AtomicInteger;
  49.  
  50. public class FunnyPrinter extends Thread {
  51.     static AtomicInteger counter = new AtomicInteger(0);
  52.  
  53.     int parity;
  54.  
  55.     public FunnyPrinter(int parity) {
  56.         super();
  57.         this.parity = parity;
  58.     }
  59.  
  60.     public void run() {
  61.         for (;;)
  62.             if (counter.intValue() % 2 == parity)
  63.                 System.out.println(counter.incrementAndGet());
  64.     }
  65.  
  66.     public static void main(String[] args) {
  67.         FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
  68.         t1.start(); t2.start();
  69.     }
  70. }
  71.        
  72. ...
  73. Thread t1=new Thread(deamonSample);
  74. try{
  75.    t1.join();
  76. }catch(InterruptedException ie){
  77.     ie.printStackTrace();
  78. }
  79. ...