java并发编程--一道经典多线程题的2种解法


  1. <span style="font-family: Helvetica, Tahoma, Arial, sans-serif; line-height: 18px; white-space: normal;">coolxing按: 转载请注明作者和出处, 如有谬误, 欢迎在评论中指正.]</span>  

问题的描述

启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:

 

线程1: 1

线程1: 2

线程1: 3

线程1: 4

线程1: 5

 

线程2: 6

线程2: 7

线程2: 8

线程2: 9

线程2: 10

...


线程3: 71

线程3: 72

线程3: 73

线程3: 74

线程3: 75

 

解法一: 采用原始的synchronized, wait(), notify(), notifyAll()等方式控制线程.

 

  1. public class NumberPrintDemo {  
  2.     // n为即将打印的数字  
  3.     private static int n = 1;  
  4.     // state=1表示将由线程1打印数字, state=2表示将由线程2打印数字, state=3表示将由线程3打印数字  
  5.     private static int state = 1;  
  6.   
  7.     public static void main(String[] args) {  
  8.         final NumberPrintDemo pn = new NumberPrintDemo();  
  9.         new Thread(new Runnable() {  
  10.             public void run() {  
  11.                 // 3个线程打印75个数字, 单个线程每次打印5个连续数字, 因此每个线程只需执行5次打印任务. 3*5*5=75  
  12.                 for (int i = 0; i < 5; i++) {  
  13.                     // 3个线程都使用pn对象做锁, 以保证每个交替期间只有一个线程在打印  
  14.                     synchronized (pn) {  
  15.                         // 如果state!=1, 说明此时尚未轮到线程1打印, 线程1将调用pn的wait()方法, 直到下次被唤醒  
  16.                         while (state != 1)  
  17.                             try {  
  18.                                 pn.wait();  
  19.                             } catch (InterruptedException e) {  
  20.                                 e.printStackTrace();  
  21.                             }  
  22.                         // 当state=1时, 轮到线程1打印5次数字  
  23.                         for (int j = 0; j < 5; j++) {  
  24.                             // 打印一次后n自增  
  25.                             System.out.println(Thread.currentThread().getName()  
  26.                                     + ": " + n++);  
  27.                         }  
  28.                         System.out.println();  
  29.                         // 线程1打印完成后, 将state赋值为2, 表示接下来将轮到线程2打印  
  30.                         state = 2;  
  31.                         // notifyAll()方法唤醒在pn上wait的线程2和线程3, 同时线程1将退出同步代码块, 释放pn锁.   
  32.                         // 因此3个线程将再次竞争pn锁  
  33.                         // 假如线程1或线程3竞争到资源, 由于state不为1或3, 线程1或线程3将很快再次wait, 释放出刚到手的pn锁.   
  34.                         // 只有线程2可以通过state判定, 所以线程2一定是执行下次打印任务的线程.  
  35.                         // 对于线程2来说, 获得锁的道路也许是曲折的, 但前途一定是光明的.  
  36.                         pn.notifyAll();  
  37.                     }  
  38.                 }  
  39.             }  
  40.         }, "线程1").start();  
  41.   
  42.         new Thread(new Runnable() {  
  43.             public void run() {  
  44.                 for (int i = 0; i < 5; i++) {  
  45.                     synchronized (pn) {  
  46.                         while (state != 2)  
  47.                             try {  
  48.                                 pn.wait();  
  49.                             } catch (InterruptedException e) {  
  50.                                 e.printStackTrace();  
  51.                             }  
  52.                         for (int j = 0; j < 5; j++) {  
  53.                             System.out.println(Thread.currentThread().getName()  
  54.                                     + ": " + n++);  
  55.                         }  
  56.                         System.out.println();  
  57.                         state = 3;  
  58.                         pn.notifyAll();  
  59.                     }  
  60.                 }  
  61.             }  
  62.         }, "线程2").start();  
  63.   
  64.         new Thread(new Runnable() {  
  65.             public void run() {  
  66.                 for (int i = 0; i < 5; i++) {  
  67.                     synchronized (pn) {  
  68.                         while (state != 3)  
  69.                             try {  
  70.                                 pn.wait();  
  71.                             } catch (InterruptedException e) {  
  72.                                 e.printStackTrace();  
  73.                             }  
  74.                         for (int j = 0; j < 5; j++) {  
  75.                             System.out.println(Thread.currentThread().getName()  
  76.                                     + ": " + n++);  
  77.                         }  
  78.                         System.out.println();  
  79.                         state = 1;  
  80.                         pn.notifyAll();  
  81.                     }  
  82.                 }  
  83.             }  
  84.         }, "线程3").start();  
  85.     }  
  86. }  

 

解法二: 采用JDK1.5并发包提供的Lock, Condition等类的相关方法控制线程.

 

  1. public class NumberPrint implements Runnable {  
  2.     private int state = 1;  
  3.     private int n = 1;  
  4.     // 使用lock做锁  
  5.     private ReentrantLock lock = new ReentrantLock();  
  6.     // 获得lock锁的3个分支条件  
  7.     private Condition c1 = lock.newCondition();  
  8.     private Condition c2 = lock.newCondition();  
  9.     private Condition c3 = lock.newCondition();  
  10.   
  11.     @Override  
  12.     public void run() {  
  13.         new Thread(new Runnable() {  
  14.             public void run() {  
  15.                 for (int i = 0; i < 5; i++) {  
  16.                     try {  
  17.                         // 线程1获得lock锁后, 其他线程将无法进入需要lock锁的代码块.  
  18.                         // 在lock.lock()和lock.unlock()之间的代码相当于使用了synchronized(lock){}  
  19.                         lock.lock();  
  20.                         while (state != 1)  
  21.                             try {  
  22.                                 // 线程1竞争到了lock, 但是发现state不为1, 说明此时还未轮到线程1打印.   
  23.                                 // 因此线程1将在c1上wait  
  24.                                 // 与解法一不同的是, 三个线程并非在同一个对象上wait, 也不由同一个对象唤醒  
  25.                                 c1.await();  
  26.                             } catch (InterruptedException e) {  
  27.                                 e.printStackTrace();  
  28.                             }  
  29.                         // 如果线程1竞争到了lock, 也通过了state判定, 将执行打印任务  
  30.                         for (int j = 0; j < 5; j++) {  
  31.                             System.out.println(Thread.currentThread().getName()  
  32.                                     + ": " + n++);  
  33.                         }  
  34.                         System.out.println();  
  35.                         // 打印完成后将state赋值为2, 表示下一次的打印任务将由线程2执行  
  36.                         state = 2;  
  37.                         // 唤醒在c2分支上wait的线程2  
  38.                         c2.signal();  
  39.                     } finally {  
  40.                         // 打印任务执行完成后需要确保锁被释放, 因此将释放锁的代码放在finally中  
  41.                         lock.unlock();  
  42.                     }  
  43.                 }  
  44.             }  
  45.         }, "线程1").start();  
  46.   
  47.         new Thread(new Runnable() {  
  48.             public void run() {  
  49.                 for (int i = 0; i < 5; i++) {  
  50.                     try {  
  51.                         lock.lock();  
  52.                         while (state != 2)  
  53.                             try {  
  54.                                 c2.await();  
  55.                             } catch (InterruptedException e) {  
  56.                                 e.printStackTrace();  
  57.                             }  
  58.                         for (int j = 0; j < 5; j++) {  
  59.                             System.out.println(Thread.currentThread().getName()  
  60.                                     + ": " + n++);  
  61.                         }  
  62.                         System.out.println();  
  63.                         state = 3;  
  64.                         c3.signal();  
  65.                     } finally {  
  66.                         lock.unlock();  
  67.                     }  
  68.                 }  
  69.             }  
  70.         }, "线程2").start();  
  71.   
  72.         new Thread(new Runnable() {  
  73.             public void run() {  
  74.                 for (int i = 0; i < 5; i++) {  
  75.                     try {  
  76.   
  77.                         lock.lock();  
  78.                         while (state != 3)  
  79.                             try {  
  80.                                 c3.await();  
  81.                             } catch (InterruptedException e) {  
  82.                                 e.printStackTrace();  
  83.                             }  
  84.                         for (int j = 0; j < 5; j++) {  
  85.                             System.out.println(Thread.currentThread().getName()  
  86.                                     + ": " + n++);  
  87.                         }  
  88.                         System.out.println();  
  89.                         state = 1;  
  90.                         c1.signal();  
  91.                     } finally {  
  92.                         lock.unlock();  
  93.                     }  
  94.                 }  
  95.             }  
  96.         }, "线程3").start();  
  97.     }  
  98.       
  99.     public static void main(String[] args) {  
  100.         new NumberPrint().run();  
  101.     }  
  102. }  

 

总结: 对比解法一和解法二, 显然解法二是更好的解决方案. 解法一的问题在于无法进行精确唤醒, 比如线程1执行完打印任务并调用pn.notifyAll()方法后, 3个线程将再次竞争锁, 而不是精确唤醒线程2. 虽然线程2最终将赢得锁, 下一次的打印任务也肯定会由线程2执行, 但是竞争的持续时间是不可预知的, 只能看线程2的人品.

最糟糕的情形可以是: 线程3竞争到了锁, 紧接着wait. 接下来线程1也竞争到了锁, 然后线程1也wait. 此时就再也没有其他线程跟线程2竞争了, 线程2终于艰难的赢得了锁...

 

留下3个问题供有兴趣的朋友思考:

1. 解法一和解法二中的while (state != xx)是否可以换成if(state != xx), 为什么?

2. 解法一的中的pn.notifyAll()是否可以换成pn.notify(), 为什么?

3. 是否可以用wait(), notify(), notifyAll()等方法完成类似解法二的精确唤醒, 请给出方案或代码.--这个问题我思考了很久, 却没有头绪. 关键的困难在于必须调用pn的wait()方法和notifyAll()方法, 而不能是其他对象的wait()和notifyAll()方法. 如果你有思路, 还望在博客中留言, 不甚感激!

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值