CSDN博客

img sapphiron

Java线程同步 1

发表于2008/9/30 21:42:00  1619人阅读

分类: Java

PART.1  ReentrantLock

 

1. 通过ReentrantLocklockunlock方法获得和释放锁。

  1. import java.util.concurrent.locks.ReentrantLock;
  2. public class ReentrantLockTest
  3. {
  4.     private static ReentrantLock locker = new ReentrantLock();
  5.     
  6.     public static void main(String[] args) throws Exception
  7.     {
  8.         Thread th = new Thread(new TestRunnable());
  9.         
  10.         System.out.println("main: lock.");
  11.         locker.lock();
  12.         
  13.         System.out.println("main: starting Test.");
  14.         th.start();
  15.         
  16.         System.out.println("main: sleep for 3 seconds.");
  17.         Thread.sleep(3000);
  18.         
  19.         System.out.println("main: unlock.");
  20.         locker.unlock();
  21.     }
  22.     
  23.     private static class TestRunnable implements Runnable
  24.     {
  25.         @Override
  26.         public void run()
  27.         {
  28.             System.out.println("test: start and lock.");
  29.             locker.lock();
  30.             System.out.println("test: between lock and unlock.");
  31.             locker.unlock();
  32.             System.out.println("test: end.");
  33.         }
  34.     }
  35. }

22个线程分别向counter10,每次加1

  1. import java.util.concurrent.locks.ReentrantLock;
  2. public class ReentrantLockTest2
  3. {
  4.     private static ReentrantLock locker = new ReentrantLock();
  5.     private static int counter = 0;
  6.     
  7.     public static void main(String[] args) throws Exception
  8.     {
  9.         Thread th1 = new Thread(new TestRunnable());
  10.         Thread th2 = new Thread(new TestRunnable());
  11.         
  12.         th1.start();
  13.         th2.start();
  14.         
  15.         th1.join();
  16.         th2.join();
  17.         
  18.         System.out.println(counter);
  19.     }
  20.     
  21.     private static class TestRunnable implements Runnable
  22.     {
  23.         @Override
  24.         public void run()
  25.         {
  26.             for (int i = 0; i < 10; i++)
  27.             {
  28.                 locker.lock();
  29.                 try
  30.                 {
  31.                     int temp = counter + 1;
  32.                     Thread.sleep(100);
  33.                     counter = temp;
  34.                 }
  35.                 catch (InterruptedException e)
  36.                 {
  37.                     return;
  38.                 }
  39.                 finally
  40.                 {
  41.                     locker.unlock();
  42.                 }
  43.             }
  44.         }
  45.     }
  46. }

PART.2 Condition

 

1.       通过ReentrantLock创建Condition对象

2.       在获得锁的条件下,调用Conditionawait方法释放锁并等待其他线程调用同一Condition对象的signal方法。

3.       另一线程在获得锁的条件下调用Condition对象的signal方法。

  1. import java.util.concurrent.locks.Condition;
  2. import java.util.concurrent.locks.ReentrantLock;
  3. public class ConditionTest
  4. {
  5.     private static ReentrantLock locker = null;
  6.     private static Condition condition = null;
  7.     
  8.     public static void main(String[] args) throws Exception
  9.     {
  10.         locker = new ReentrantLock();
  11.         condition = locker.newCondition();
  12.         
  13.         Thread th = new Thread(new TestRunnable());
  14.         th.start();
  15.         
  16.         Thread.sleep(3000);
  17.         
  18.         System.out.println("main: signal all.");
  19.         // 调用condition.signalAll()将使Test线程中的阻塞结束。
  20.         locker.lock();
  21.         condition.signalAll();
  22.         locker.unlock();
  23.         
  24.         System.out.println("main: end.");
  25.     }
  26.     
  27.     private static class TestRunnable implements Runnable
  28.     {
  29.         @Override
  30.         public void run()
  31.         {
  32.             locker.lock();
  33.             try
  34.             {
  35.                 System.out.println("test: before 'condition.await()'");
  36.                 
  37.                 // await()将阻塞直到其他线程调用condition.signal。
  38.                 condition.await();
  39.                 
  40.                 System.out.println("test: after 'condition.await()'");
  41.                 Thread.sleep(1000);
  42.             }
  43.             catch (InterruptedException e)
  44.             {
  45.             }
  46.             finally 
  47.             {
  48.                 locker.unlock();
  49.             }
  50.         }
  51.     }
  52. }

生产者与消费者示例

 

  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. import java.util.concurrent.locks.Condition;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. public class ConditionTest2
  6. {
  7.     private static ReentrantLock locker;
  8.     private static Condition condition;
  9.     private static Queue<Integer> queue;
  10.     
  11.     public static void main(String[] args) throws Exception
  12.     {
  13.         locker = new ReentrantLock();
  14.         condition = locker.newCondition();
  15.         queue = new LinkedList<Integer>();
  16.         
  17.         Thread pth = new ProducerThread();
  18.         Thread cth = new ConsumerThread();
  19.         
  20.         pth.start();
  21.         cth.start();
  22.         
  23.         Thread.sleep(30 * 1000);
  24.         
  25.         pth.interrupt();
  26.         cth.interrupt();
  27.         
  28.         pth.join();
  29.         cth.join();
  30.     }
  31.     
  32.     
  33.     private static class ProducerThread extends Thread
  34.     {
  35.         @Override
  36.         public void run()
  37.         {
  38.             // 每0-500毫秒产生一个随机整数并加入队列。
  39.             while (!Thread.currentThread().isInterrupted())
  40.             {
  41.                 locker.lock();
  42.                 try
  43.                 {
  44.                     int x = (int)(Math.random() * 100);
  45.                     queue.offer(x);
  46.                     condition.signalAll();
  47.                     System.out.println("producer: " + x + ", signal all");
  48.                     // 随机休眠0-499毫秒
  49.                     Thread.sleep((int)(Math.random() * 500));
  50.                 }
  51.                 catch (InterruptedException e)
  52.                 {
  53.                     break;
  54.                 }
  55.                 finally 
  56.                 {
  57.                     locker.unlock();
  58.                 }
  59.             }
  60.             System.out.println("End of ProducerThread.");
  61.         }
  62.     }
  63.     
  64.     private static class ConsumerThread extends Thread
  65.     {
  66.         @Override
  67.         public void run()
  68.         {
  69.             // 每0-500毫秒从队列取出一个数并输出。
  70.             while (!Thread.currentThread().isInterrupted())
  71.             {
  72.                 locker.lock();
  73.                 try
  74.                 {
  75.                     // 如果队列为空,将等待ProducerThread向队列插入数据。
  76.                     while (queue.isEmpty())
  77.                     {
  78.                         System.out.println("consumer: Queue is empty.");
  79.                         condition.await();
  80.                     }
  81.                     int x  = queue.poll();
  82.                     System.out.println("consumer: " + x);
  83.                     
  84.                     // 随机休眠0-499毫秒
  85.                     Thread.sleep((int)(Math.random() * 500));
  86.                 }
  87.                 catch (InterruptedException e)
  88.                 {
  89.                     break;
  90.                 }
  91.                 finally
  92.                 {
  93.                     locker.unlock();
  94.                 }
  95.             }
  96.             System.out.println("End of ComsumerThread.");
  97.         }
  98.     }
  99. }

 

0 0

相关博文

我的热门文章

img
取 消
img