JAVA线程同步

  1. public static void main(String[] args) {
  2.         ThreadGroup g=new ThreadGroup("test");
  3.         Thread t=null;
  4.         for(int i=0;i<1000;i++)
  5.         {
  6.             t=new Thread(g,new R_impl(),i+"");
  7.             t.start();
  8.         }
  9.     }
  10. class R_impl implements Runnable
  11. {
  12.     public static int count=1;
  13. //public volatile int count=1;
  14.     public static Lock myLock=new ReentrantLock();
  15.     public static Condition cond=myLock.newCondition();
  16.     public static Object obj=new Object();
  17.   
    1. public void run() // public volatile int count=1;
    2.     {
    3.         try
    4.         { 
    5.                 count--;
    6.                 System.out.println(count);
    7.                 count++;
    8.                 System.out.println(count);
    9.         }catch(Exception ex)
    10.         {
    11.             ex.printStackTrace();
    12.         }
    13.     }
        
    public void run()
  18.     {
  19.         try
  20.         {
  21.             synchronized (obj) {
  22.                 count--;
  23.                 System.out.println(count);
  24.                 count++;
  25.                 System.out.println(count);
  26.             }   
  27.         }catch(Exception ex)
  28.         {
  29.             ex.printStackTrace();
  30.         }
  31.     }
  32.     public synchronized void run()
  33.     {
  34.         try
  35.         {
  36.         if(count<=0)
  37.             this.wait();
  38.         count--;
  39.         System.out.println(count);
  40.         count++;
  41.         this.notifyAll();
  42.         System.out.println(count);
  43.         }catch(Exception ex)
  44.         {
  45.             ex.printStackTrace();
  46.         }
  47.     }
  48.     public  void run()
  49.     {
  50.         try
  51.         {
  52.         myLock.lock();
  53.         count--;
  54.         System.out.println(count);
  55.         count++;
  56.         System.out.println(count);
  57.         myLock.unlock();
  58.         }catch(Exception ex)
  59.         {
  60.             ex.printStackTrace();
  61.         }
  62.     }
  63.     public  void run()
  64.     {
  65.         myLock.lock();
  66.         try
  67.         {
  68.         if(count<=0)
  69.             cond.await();
  70.         count--;
  71.         System.out.println(count);
  72.         count++;
  73.         System.out.println(count);
  74.             cond.signalAll();
  75.         }catch(Exception ex)
  76.         {
  77.             ex.printStackTrace();
  78.         }finally
  79.         {
  80.             myLock.unlock();
  81.         }
  82.     }
  83. }

你可能感兴趣的:(java,String)