鍍金池/ 教程/ Java/ Java并發(fā)同步
Java并發(fā)死鎖
Java并發(fā)主要操作
Java并發(fā)BlockingQueue接口
Java并發(fā)線程間通信
Java并發(fā)ThreadLocal類
Java并發(fā)newCachedThreadPool方法
Java并發(fā)Futures和Callables類
Java并發(fā)AtomicLongArray類
Java并發(fā)開發(fā)環(huán)境配置
Java并發(fā)ExecutorService接口
Java并發(fā)ConcurrentMap接口
Java并發(fā)AtomicReferenceArray類
Java并發(fā)AtomicLong接口
Java并發(fā)AtomicReference類
Java并發(fā)同步
Java并發(fā)newFixedThreadPool方法
Java并發(fā)編程教程
Java并發(fā)Condition接口
Java并發(fā)newScheduledThreadPool()方法
Java并發(fā)fork-join框架
Java并發(fā)newSingleThreadExecutor()方法
Java并發(fā)Lock接口
Java并發(fā)ThreadPoolExecutor類
Java并發(fā)ConcurrentNavigableMap接口
Java并發(fā)ScheduledThreadPoolExecutor類
Java并發(fā)ReadWriteLock接口
Java并發(fā)AtomicIntegerArray類
Java并發(fā)Executor接口
Java并發(fā)ThreadLocalRandom類
Java并發(fā)AtomicBoolean類
Java并發(fā)ScheduledExecutorService接口
Java并發(fā)是什么?
Java并發(fā)AtomicBoolean類

Java并發(fā)同步

下面是一個具有同步功能的多線程示例,這是和上篇文章同樣的例子,它依次打印計數(shù)器值,每次運行它時,它產生相同的結果。

實例

class PrintDemo {
   public void printCount() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      }catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;

   ThreadDemo( String name,  PrintDemo pd) {
      threadName = name;
      PD = pd;
   }

   public void run() {
      synchronized(PD) {
         PD.printCount();
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      PrintDemo PD = new PrintDemo();

      ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
      ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

      T1.start();
      T2.start();

      // wait for threads to end
      try {
         T1.join();
         T2.join();
      }catch( Exception e) {
         System.out.println("Interrupted");
      }
   }
}

每次運行此程序時都會產生相同的結果 -

Starting Thread - 1
Starting Thread - 2
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 1  exiting.
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 2  exiting.