ThreadTest.java


public class ThreadTest implements Runnable{

   // volatile is supposed let JVM not use cache to store the variable value
   // You always get the real time value of the variable (not from cache)
   // used for mission critical (real time) variables
   static volatile int i1, i2, j1, j2, k1, k2;
   
   public void run() {
      while (true){
         safeDoSomething();
         
         // Use checkResult() or safeCheckResult()
         // you will see different output
         checkResult();
         //safeCheckResult(); 
      }
   }
   
   synchronized void safeDoSomething() {
      i1++; j1++; k1++; i2++; j2++; k2++;
   }
   
   void checkResult() {
      if (i1 != i2)
         System.out.println("i1 != i2");
      if (j1 != j2)
         System.out.println("j1 != j2");
      if (k1 != k2)
         System.out.println("k1 != k2");
   }
   
   synchronized void safeCheckResult() {
      if (i1 != i2)
         System.out.println("i1 != i2");
      if (j1 != j2)
         System.out.println("j1 != j2");
      if (k1 != k2)
         System.out.println("k1 != k2");
   }

   public static void main (String[] args){
      ThreadTest t = new ThreadTest();
      
      Thread t1 = new Thread(t);
      Thread t2 = new Thread(t);
      Thread t3 = new Thread(t);
      
      t1.setDaemon(true);
      t2.setDaemon(true);
      t3.setDaemon(true);
      
      t1.start();
      t2.start();
      t3.start();
      
      try {
         // let daemon threads run
         Thread.sleep(10000);
      }
      catch (InterruptedException e) {
      }
      System.out.println("If user thread is dead, all daemon threads die. ");
   }
}

last updated: 10-16-1999
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]