CSDN博客

img sapphiron

Java线程同步 3

发表于2008/10/2 20:02:00  557人阅读

1. CountDownLatch

  1. CountDownLatch用于等待计数器计数。
  2. 在创建CountDownLatch时指定初始的整数。
  3. 调用CountDownLatch的await方法等待计数器到0。
  4. 每调用一次CountDownLatch的countDown方法,计数器减1。
  1. import java.util.concurrent.CountDownLatch;
  2. public class CountDownLatchTest
  3. {
  4.     private static CountDownLatch counter = null;
  5.     public static void main(String[] args) throws Exception
  6.     {
  7.         counter = new CountDownLatch(10);
  8.         Thread th1 = new Thread(new TestRunnable(), "thread 1");
  9.         Thread th2 = new Thread(new TestRunnable(), "thread 2");
  10.         th1.start();
  11.         th2.start();
  12.         counter.await();
  13.         System.out.println("main: after counter.await().");
  14.         th1.interrupt();
  15.         th2.interrupt();
  16.         th1.join();
  17.         th2.join();
  18.         System.out.println("main: end.");
  19.     }
  20.     private static class TestRunnable implements Runnable
  21.     {
  22.         @Override
  23.         public void run()
  24.         {
  25.             String thName = Thread.currentThread().getName();
  26.             System.out.printf("%s: start. /n", thName);
  27.             try
  28.             {
  29.                 while (true)
  30.                 {
  31.                     // 随机等待1-5秒
  32.                     int t = (int) (Math.random() * 5 + 1);
  33.                     System.out.printf("%s: sleep for %d seconds./n", thName, t);
  34.                     Thread.sleep(1000 * t);
  35.                     // 计数
  36.                     counter.countDown();
  37.                 }
  38.             }
  39.             catch (InterruptedException e)
  40.             {
  41.                 System.out.printf("%s: interrupted. /n", thName);
  42.             }
  43.             System.out.printf("%s: end. /n", thName);
  44.         }
  45.     }
  46. }

2. Exchanger

  1. Exchanger用于在2个线程中交换对象。
  2. an_object = exchanger.exchange(an_object)
  3. 例子中Producer向ArrayList中缓慢填充随机整数,Consumer从另一个ArrayList中缓慢取出整数并输出。
  4. 当Producer的ArrayList填满,并且Consumer的ArrayList为空时,2个线程交换ArrayList。 
  1. import java.util.ArrayList;
  2. import java.util.concurrent.Exchanger;
  3. public class ExchangerTest
  4. {
  5.     private static Exchanger<ArrayList<Integer>> exchanger = null;
  6.     private static ArrayList<Integer> buffer1 = null;
  7.     private static ArrayList<Integer> buffer2 = null;
  8.     public static void main(String[] args) throws Exception
  9.     {
  10.         exchanger = new Exchanger<ArrayList<Integer>>();
  11.         buffer1 = new ArrayList<Integer>(10);
  12.         buffer2 = new ArrayList<Integer>(10);
  13.         Thread pth = new ProducerThread();
  14.         Thread cth = new ConsumerThread();
  15.         pth.start();
  16.         cth.start();
  17.         Thread.sleep(60 * 1000);
  18.         System.out.println("main: interrupting threads.");
  19.         pth.interrupt();
  20.         cth.interrupt();
  21.         pth.join();
  22.         cth.join();
  23.         System.out.println("main: end.");
  24.     }
  25.     private static class ProducerThread extends Thread
  26.     {
  27.         @Override
  28.         public void run()
  29.         {
  30.             ArrayList<Integer> buff = buffer1;
  31.             try
  32.             {
  33.                 while (true)
  34.                 {
  35.                     if (buff.size() >= 10)
  36.                     {
  37.                         // 与consumer交换buffer.
  38.                         System.out.println("producer: exchanging.");
  39.                         buff = exchanger.exchange(buff);
  40.                         buff.clear();
  41.                     }
  42.                     // 随机产生一个0-100的整数。
  43.                     int x = (int) (Math.random() * 100);
  44.                     buff.add(x);
  45.                     System.out.println("producer: " + x);
  46.                     // 随机等待0-3秒 。
  47.                     int t = (int) (Math.random() * 3);
  48.                     Thread.sleep(t * 1000);
  49.                 }
  50.             }
  51.             catch (InterruptedException e)
  52.             {
  53.                 System.out.println("producer: interrupted.");
  54.             }
  55.         }
  56.     }
  57.     private static class ConsumerThread extends Thread
  58.     {
  59.         @Override
  60.         public void run()
  61.         {
  62.             ArrayList<Integer> buff = buffer2;
  63.             try
  64.             {
  65.                 while (true)
  66.                 {
  67.                     for (Integer x : buff)
  68.                     {
  69.                         System.out.println("consumer: " + x);
  70.                         // 随机等待0-3秒 。
  71.                         int t = (int) (Math.random() * 3);
  72.                         Thread.sleep(t * 1000);
  73.                     }
  74.                     // 与producer交换buffer。
  75.                     System.out.println("consumer: exchanging.");
  76.                     buff = exchanger.exchange(buff);
  77.                 }
  78.             }
  79.             catch (InterruptedException e)
  80.             {
  81.                 System.out.println("consumer: interrupted.");
  82.             }
  83.         }
  84.     }
  85. }

3. Semaphore

  1. Semaphore对象保存n个许可。(在构造方法指定)
  2. 一个线程可以从Semahpore中取出x个许可,当Semaphore对象中的许可数量不足x时将阻塞。
  3. 线程使用完许可后将许可归还给Semaphore。
  1. import java.util.ArrayList;
  2. import java.util.concurrent.Semaphore;
  3. public class SemaphoreTest
  4. {
  5.     private static Semaphore semaphore = null;
  6.     private static ArrayList<TestThread> threads = null;;
  7.     private static ThreadGroup group = null;
  8.     public static void main(String[] args) throws Exception
  9.     {
  10.         semaphore = new Semaphore(10);
  11.         threads = new ArrayList<TestThread>(5);
  12.         group = new ThreadGroup("no name");
  13.         for (int i = 0; i < 5; i++)
  14.         {
  15.             TestThread th = new TestThread("thread " + i, group);
  16.             threads.add(th);
  17.             th.start();
  18.         }
  19.         for (int i = 0; i < 60; i++)
  20.         {
  21.             System.out.println(i + " :/t" + getStatus());
  22.             Thread.sleep(1000);
  23.         }
  24.         group.interrupt();
  25.     }
  26.     private static String getStatus()
  27.     {
  28.         StringBuffer sb = new StringBuffer();
  29.         for (int i = 0; i < 5; i++)
  30.         {
  31.             sb.append(threads.get(i).getStatus());
  32.             sb.append("/t");
  33.         }
  34.         sb.append(":");
  35.         sb.append(10 - semaphore.availablePermits());
  36.         return sb.toString();
  37.     }
  38.     private static class TestThread extends Thread
  39.     {
  40.         private String status = "";
  41.         public String getStatus()
  42.         {
  43.             return status;
  44.         }
  45.         public TestThread(String name, ThreadGroup group)
  46.         {
  47.             super(group, name);
  48.         }
  49.         @Override
  50.         public void run()
  51.         {
  52.             String thName = Thread.currentThread().getName();
  53.             System.out.printf("%s: started. /n", thName);
  54.             try
  55.             {
  56.                 while (true)
  57.                 {
  58.                     int p = (int) (Math.random() * 4) + 1;
  59.                     status = "[" + p + "]";
  60.                     semaphore.acquire(p);
  61.                     status = " " + p + " ";
  62.                     Thread.sleep((long) (Math.random() * 3000) + 2000);
  63.                     semaphore.release(p);
  64.                 }
  65.             }
  66.             catch (InterruptedException e)
  67.             {
  68.                 System.out.printf("%s: interrupted. /n", thName);
  69.             }
  70.         }
  71.     }
  72. } 
阅读全文
0 0

相关文章推荐

img
取 消
img