问题的描述

启动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....以此类推, 直到打印到45.

wait+notify实现:

package com.tonyluis;
public class NumberPrintDemo {
static int n = 1;
static int state = 0;
public static void main(String[] args) {
new Thread(new MyThread(0)).start();
new Thread(new MyThread(1)).start();
new Thread(new MyThread(2)).start();
}
} class MyThread implements Runnable{
private int state;
MyThread(){
this(0);
}
MyThread(int state){
this.state=state;
}
public void run() {
String threadName=Thread.currentThread().getName();
for (int i = 0; i < 3; i++) {
synchronized (MyThread.class) {
while (state != NumberPrintDemo.state)
try {
MyThread.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++)
System.out.println(threadName+ ": " + NumberPrintDemo.n++);
System.out.println();
NumberPrintDemo.state++;
NumberPrintDemo.state%=3;
MyThread.class.notifyAll();
}
}
}
}

Lock+condition实现:

package com.tonyluis;
import java.util.concurrent.locks.*;
public class NumberPrint {
static int state = 0;
static int n = 1;
static Lock lock = new ReentrantLock();
static Condition condition[]=new Condition[3];
public static void main(String[] args) {
for(int i=0;i<condition.length;i++)
condition[i]=lock.newCondition();
NumberPrint np=new NumberPrint(); new Thread(np.new MyThread(0)).start();
new Thread(np.new MyThread(1)).start();
new Thread(np.new MyThread(2)).start();
} class MyThread implements Runnable{
private int state;
MyThread(){
this(0);
}
MyThread(int state){
this.state=state;
}
public void run() {
String threadName=Thread.currentThread().getName();
for (int i = 0; i < 7; i++) {
//不需要放到finnally{}中释放锁,因为后面await()会释放锁
NumberPrint.lock.lock();
while (state != NumberPrint.state)
try {
NumberPrint.condition[state].await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 5; j++)
System.out.println(threadName+ ": " + NumberPrint.n++);
System.out.println();
NumberPrint.state++;
NumberPrint.state%=NumberPrint.condition.length;
NumberPrint.condition[NumberPrint.state].signal();
try {
NumberPrint.condition[state].await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

使用wait+notify的实现方式,在线程0进入notifyAll()方法之后,会唤醒线程1和线程2,线程1和线程2以及线程0会展开竞争,虽然最终是由线程1获得琐,过程可能比较曲折。

使用lock+condition的实现方法,线程0只会唤醒线程1,同时进入await()方法释放锁,这样只有线程1能够执行,非常的精确,尤其是并发量比较大的情况下。

Lock+Condition 相对于 wait+notify 的一个优势案例分析的更多相关文章

  1. 一个bug案例分析

    Bug描述: 某大型系统的一个提供基础数据服务的子系统A进行了一次升级.升级的内容为:优化了失败重传功能,在优化的同时,开发人员发现传输数据的时间戳精度只是精确到了秒,于是顺手把精度改成了1/100秒 ...

  2. javascript一个作用域案例分析

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 生产者消费者两种实现:wait/notifyAll和Lock/Condition

    1.wait/notifyAll /** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用 ...

  4. Java多线程——Lock&Condition

    Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象.两个线程执行的代码片段要实现同步互斥的效果,它们必须用同一个Lock对象. package ...

  5. lock+Condition

    关键字 synchronized+wait/notify/notifyAll可以实现等待/通知模式,类ReentrantLock可以实现同样的功能,但需要借助Condition对象.Condition ...

  6. Lock+Condition实现机制

    前言:大部分多线程同步场景,在功能和性能层面,synchronized可以满足,少部分场景Lock可以满足,dubbo的源码也符合这个比例,需要使用到Condition的场景极少,整个dubbo源码中 ...

  7. 【java并发编程】Lock & Condition 协调同步生产消费

    一.协调生产/消费的需求 本文内容主要想向大家介绍一下Lock结合Condition的使用方法,为了更好的理解Lock锁与Condition锁信号,我们来手写一个ArrayBlockingQueue. ...

  8. 玩转Java多线程(Lock.Condition的正确使用姿势)

    转载请标明博客的地址 本人博客和github账号,如果对你有帮助请在本人github项目AioSocket上点个star,激励作者对社区贡献 个人博客:https://www.cnblogs.com/ ...

  9. NOTIFY - 生成一个通知

    SYNOPSIS NOTIFY name DESCRIPTION 描述 NOTIFY 命令向当前数据库中所有执行过 LISTEN name, 正在监听特定通知条件的前端应用发送一个通知事件. 传递给前 ...

随机推荐

  1. Linux下的微秒级定时器: usleep, nanosleep, select, pselect

    Linux下的微秒级定时器: usleep, nanosleep, select, pselect 标签: linuxnulldelaystructdate 2012-02-07 23:29 4979 ...

  2. HTML5+CSS3+jquery实现简单的音乐播放器

    ...最近天热的,感觉就像煎饼...然后别人在把妹子的时候,只有偶们这帮苦逼的程序员在那边撸代码...我日哦! 然后今天晒的是偶早年写的一个播放器...看上去是不是很有感觉的样子!一番宝物,Lisa唱 ...

  3. 避免重定向301&302 (Avoid Redirects)

    这个也是Best Practices for Speeding Up Your Web Site的第12条原则: 重定向的意思是,用户的原始请求(例如请求A)被重定向到其他的请求(例如请求B).这是H ...

  4. [译]Mongoose指南 - 中间件

    中间件是一些函数, 当document发生init, validate, save和remove方法的时候中间件发生. 中间件都是document级别的不是model级别的. 下面讲讲两种中间件pre ...

  5. c#后台替换html标签的方法

     public static string ReplaceHtmlTag(string html)         {              string strText = System.Tex ...

  6. vs 工程连接错误

    现象: estMemPool.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: _ ...

  7. 【C语言入门教程】7.5 枚举

    在实际应用中,有的变量只有几种可能取值.如人的性别只有两种可能取值,星期只有七种可能取值.在 C 语言中对这样取值比较特殊的变量可以定义为枚举类型.所谓枚举是指将变量的值一一列举出来,变量只限于列举出 ...

  8. C++ 传参数 拉起程序

    ShellExecute(NULL,_T("open"),_T("Update.exe"),"Own",NULL,SW_HIDE);

  9. FineUI第十二天---锚点布局

    锚点布局的典型结构: <x:Panel Layout="Anchor" runat="server">              <Items ...

  10. wp手机 htc x310e

    入手htc x310e 手机不错,用着流畅 不习惯,已升到wp7.8,系统限制还是有些需要的功能没有,比如说短信拦截什么的 我需要的常用软件少 转手了 1 注销windows live? 设置--应用 ...