Facebook
From Ample Earthworm, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 210
  1. package Paradigms.List11.CommonStaticVariableResolvings;
  2.  
  3.  
  4.  
  5. public class IntCellDefault {
  6.  
  7.     public int getN(){
  8.  
  9.         return n;
  10.  
  11.     }
  12.  
  13.  
  14.  
  15.     public void setN(int n){
  16.  
  17.         this.n = n;
  18.  
  19.     }
  20.  
  21.  
  22.  
  23.     private int n = 0;
  24.  
  25. }
  26.  
  27.  
  28.  
  29. class Count extends Thread{
  30.  
  31.     static IntCellDefault n = new IntCellDefault();
  32.  
  33.  
  34.  
  35.     @Override
  36.  
  37.     public void run(){
  38.  
  39.         for (int i = 0; i < 200000; i++){
  40.  
  41.             int temp = n.getN();
  42.  
  43.             n.setN(temp+1);
  44.  
  45.         }
  46.  
  47.     }
  48.  
  49.  
  50.  
  51.     public static void main(String[] args){
  52.  
  53.         Count thread1 = new Count();
  54.  
  55.         Count thread2 = new Count();
  56.  
  57.         thread1.start();
  58.  
  59.         thread2.start();
  60.  
  61.         try{
  62.  
  63.             thread1.join();
  64.  
  65.             thread2.join();
  66.  
  67.         }catch(InterruptedException e){
  68.  
  69.             System.out.println(e.getStackTrace());
  70.  
  71.             System.out.println("Catched exception");
  72.  
  73.         }
  74.  
  75.         System.out.println("The value of n is " + n.getN());
  76.  
  77.     }
  78.  
  79.  
  80.  
  81.     // First of all thread1 and thread2 starts in various times
  82.  
  83.     // Secondly each thread makes a copy to their local caches
  84.  
  85.     // It implies that when thread1 modifies the static variable
  86.  
  87.     // The thread2 can contain old value of static variable
  88.  
  89.     // And will increase basing on old value
  90.  
  91.     // Then finally cause that the value of n.n has lower value then expected 400000
  92.  
  93.     //
  94.  
  95.     // Exception
  96.  
  97.     // InterruptedException is cought for the security because JVM can sometimes throw it
  98.  
  99.     // But common situation is when someone will call interrupt(przerwij) on this thread
  100.  
  101.     //
  102.  
  103.     // Join
  104.  
  105.     // Wait for this thread to die
  106.  
  107. }