jdk线程的生产者消费者问题
同步代码块实现生产者消费者模式
class Person {
private String name;
private String sex;
private Boolean isEmpty = Boolean.TRUE; // 表示存储区域是否为空 //生产
public void set(String name, String sex) {
synchronized (this) {
// if(isEmpty)
while (!isEmpty.equals(Boolean.TRUE)) {
// 区域不为空,此时生产者应该停下来,等着消费者消费
try {this.wait();// 等待 消费者消费} catch (InterruptedException e) {}
}
this.name = name;
try {Thread.sleep(1); } catch (InterruptedException e) {e.printStackTrace();}
this.sex = sex;
// 生产者生产之后,应该修改存储区域的状态
isEmpty = Boolean.FALSE;// 不为空
this.notifyAll();// 唤醒消费者,起来吃东西了
}
} //消费
public void get() {
synchronized (this) {
// 存储区域为空
while (!isEmpty.equals(Boolean.FALSE)) {
try {this.wait();// 等着生产者去生产} catch (InterruptedException e) {}
}
String name = getName();
String sex = getSex();
System.out.println(name + " --> " + sex);
// 消费完成,应该修改存储区域的状态
isEmpty = Boolean.TRUE;// 空了
this.notifyAll();// 唤醒生产者,
}
}
getter/setter
} //生产者
class Producer implements Runnable {
private Person p;
public Producer(Person p) {
this.p = p;
} public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
p.set("春哥哥", "男");
} else {
p.set("著姐", "女");
}
}
}
}
//消费者
class Consumer implements Runnable {
private Person p;
public Consumer(Person p) {
this.p = p;
}
public void run() {
for (int i = 0; i < 100; i++) {
p.get();
}
}
} public class Producer_ConsumerDemo {
public static void main(String[] args) {
Person p = new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
同步方法实现生产者消费者模式
class Person {
private String name;
private String sex;
private Boolean isEmpty = Boolean.TRUE; // 表示存储区域是否为空
//生产
public synchronized void set(String name, String sex) {
// if(isEmpty)
while (!isEmpty.equals(Boolean.TRUE)) {
// 区域不为空,此时生产者应该停下来,等着消费者消费
try {this.wait();// 等待 消费者消费} catch (InterruptedException e) {}
}
this.name = name;
try {Thread.sleep(1); } catch (InterruptedException e) {}
this.sex = sex;
// 生产者生产之后,应该修改存储区域的状态
isEmpty = Boolean.FALSE;// 不为空
this.notifyAll();// 唤醒消费者,起来吃东西了
} //消费
public synchronized void get() {
// 存储区域为空
while (!isEmpty.equals(Boolean.FALSE)) {
try {this.wait();// 等着生产者去生产} catch (InterruptedException e) {}
}
String name = getName();
String sex = getSex();
System.out.println(name + " --> " + sex);
// 消费完成,应该修改存储区域的状态
isEmpty = Boolean.TRUE;// 空了
this.notifyAll();// 唤醒生产者,
}
getter/setter
} //生产者
class Producer implements Runnable {
private Person p;
public Producer(Person p) {
this.p = p;
}
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
p.set("春哥哥", "男");
} else {
p.set("著姐", "女");
}
}
}
} class Consumer implements Runnable {
private Person p;
public Consumer(Person p) {
this.p = p;
}
public void run() {
for (int i = 0; i < 100; i++) {
p.get();
}
}
}
public class Producer_ConsumerDemo {
public static void main(String[] args) {
Person p = new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
可重入锁实现生产者消费者模式
jkd1.5后的另一种同步机制:通过显示定义同步锁对象来实现同步,这种机制,同步锁应该使用Lock对象充当;
在实现线程安全控制中,通常使用ReentrantLock(可重入锁)。使用该对象可以显示地加锁和解锁;
具有与使用 synchronized 方法和语句所访问的隐式监视器锁相同的一些基本行为和语义,但功能更强大。
格式:
public class X {
private final ReentrantLock lock = new ReentrantLock();
//定义需要保证线程安全的方法
public void m(){
lock.lock();//加锁
try{
//... method body
}finally{
lock.unlock();//在finally释放锁
}
}
}
可重入锁没有同步监听对象,咋办呢?
Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
class Person {
private final ReentrantLock lock = new ReentrantLock();// 创建可重入锁对象
private final Condition con = lock.newCondition(); private String name; private String sex;
private Boolean isEmpty = Boolean.TRUE; // 表示存储区域是否为空 //生产
public void set(String name, String sex) {
lock.lock();
while(!isEmpty.equals(Boolean.TRUE)){ //表示不空状态
try {con.await();} catch (InterruptedException e) {}}
try {
this.name = name;
Thread.sleep(1);
this.sex = sex;
isEmpty = Boolean.FALSE;
con.signal();
} catch (InterruptedException e) {} finally {
lock.unlock();
}
} //消费
public void get() {
lock.lock();
while(!isEmpty.equals(Boolean.FALSE)){ //存储区域为空,消费者应该等着
try {
con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
String name = getName();
String sex = getSex();
System.out.println(name + " --> " + sex);
//
isEmpty = Boolean.TRUE;
con.signal();
} finally {
lock.unlock();
} }
getter/setter
} //生产者
class Producer implements Runnable {
private Person p;
public Producer(Person p) {
this.p = p;
} public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
p.set("春哥哥", "男");
} else {
p.set("著姐", "女");
}
}
}
} class Consumer implements Runnable {
private Person p;
public Consumer(Person p) {
this.p = p;
}
public void run() {
for (int i = 0; i < 100; i++) {
p.get();
}
}
} public class Producer_ConsumerDemo {
public static void main(String[] args) {
Person p = new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
同步代码块方式改写卖票程序
class MyRunnable implements Runnable {
private Integer num = 50;
public void run() {
for (int i = 0; i < 200; i++) {
sale();
}
}
private Object o = new Object(); public void sale() {
// synchronized (this) {
// synchronized (MyRunnable.class) {
synchronized (o) {
if (num > 0) {
try {Thread.sleep(1); } catch (InterruptedException e) {}
System.out.println(Thread.currentThread().getName() + "卖出第"
+ num-- + "张");
}
}
}
} public class TicketDemoSyncByBlock {
public static void main(String[] args) {
Runnable target = new MyRunnable();
new Thread(target, "A").start();
new Thread(target, "B").start();
new Thread(target, "C").start();
}
}
实现Runnable接口的方式,使用同步代码块的方式进行同步。
可以取的同步监听对象为:this、当前方法所在类的Class对象、任一不变对象;
同步方法方式改写卖票程序
class MyRunnable implements Runnable {
private Integer num = 50;
public void run() {
for (int i = 0; i < 200; i++) {
sale();
}
} synchronized public void sale() {
if (num > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出第" + num-- + "张");
}
}
} public class TicketDemoSyncByMethod {
public static void main(String[] args) {
Runnable target = new MyRunnable();
new Thread(target, "A").start();
new Thread(target, "B").start();
new Thread(target, "C").start();
}
}
可重入锁方式改写卖票程序
class MyRunnable implements Runnable { private final ReentrantLock lock = new ReentrantLock();
private Integer num = 50; public void run() {
for (int i = 0; i < 200; i++) {
sale();
}
} public void sale() {
lock.lock();
try {
if (num > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖出第"
+ num-- + "张");
}
} finally {
lock.unlock();
}
}
} public class TicketDemoSyncByReentrantLock {
public static void main(String[] args) {
Runnable target = new MyRunnable();
new Thread(target, "A").start();
new Thread(target, "B").start();
new Thread(target, "C").start();
}
}
jdk线程的生产者消费者问题的更多相关文章
- 第23章 java线程通信——生产者/消费者模型案例
第23章 java线程通信--生产者/消费者模型案例 1.案例: package com.rocco; /** * 生产者消费者问题,涉及到几个类 * 第一,这个问题本身就是一个类,即主类 * 第二, ...
- .net学习之多线程、线程死锁、线程通信 生产者消费者模式、委托的简单使用、GDI(图形设计接口)常用的方法
1.多线程简单使用(1)进程是不执行代码的,执行代码的是线程,一个进程默认有一个线程(2)线程默认情况下都是前台线程,要所有的前台线程退出以后程序才会退出,进程里默认的线程我们叫做主线程或者叫做UI线 ...
- Java如何使用线程解决生产者消费者问题?
在Java编程中,如何使用线程解决生产者消费者问题? 以下示例演示如何使用线程解决生产者消费者问题. package com.yiibai; public class ProducerConsumer ...
- Java多线程-同步:synchronized 和线程通信:生产者消费者模式
大家伙周末愉快,小乐又来给大家献上技术大餐.上次是说到了Java多线程的创建和状态|乐字节,接下来,我们再来接着说Java多线程-同步:synchronized 和线程通信:生产者消费者模式. 一.同 ...
- java线程之生产者消费者
看了毕向东老师的生产者消费者,就照着视频参考运行了一下,感觉还好 这个值得学习的是条理特别清晰: ProducterConsumerDemo.java中,一个资源类Resources,生产者消费者都可 ...
- 线程锁,threadinglocal,线程池,生产者消费者模型
1.线程锁 1.锁Lock(只能锁一次) import threading import time v = [] lock = threading.Lock() def func(arg): lock ...
- Java线程通信-生产者消费者问题
线程通信示例——生产者消费者问题 这类问题描述了一种情况,假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中的产品取走消费.假设仓库中没有产品,则生产者可以将 产品放入仓库,有 ...
- Java 线程池 +生产者消费者+MySQL读取300 万条数据
1.1需求 数据库300 万条用户数据 ,遍历获取所有用户, 各种组合关联, 获取到一个新的json ,存到redis 上. 1.2 难点 数据库比较多, 不可能单线程查询所有的数据到内存. 1.3解 ...
- Python自动化--语言基础7--操作日志、加密、发送邮件、线程、生产者消费者
1.操作日志 logging.basicConfig:日志的统一处理器,对日志的输出格式和方式做配置日志级别等级CRITICAL > ERROR > WARNING > INFO & ...
随机推荐
- TTL电平和CMOS电平总结
TTL电平和CMOS电平总结 1,TTL电平: 输出高电平>2.4V,输出低电平<0.4V.在室温下,一般输出高电平是3.5V,输出低电平是0.2V.最小输入高电平和低电 ...
- 【转】JVM 分代GC策略分析
我们以Sun HotSpot VM来进行分析,首先应该知道,如果我们没有指定任何GC策略的时候,JVM默认使用的GC策略.Java虚拟机是按照分代的方式来回收垃圾空间,我们应该知道,垃圾回收主要是针对 ...
- Dell R410 broadcom网卡驱动更新失败
问题描述: 最近遇到一个Dell R410 broadcom网卡驱动更新失败的问题.从官网上下载的驱动在安装的过程中都会自己回滚回来,很是困惑. 尝试解决: Dell官网现在提供的驱动一般最少有两种格 ...
- Windows Server 2008 - How to Move the Quorum Disk Group
I received this question from a friend the other day - asking how on a Windows Server 2008 cluster y ...
- HDMI的CEC是如何控制外围互联设备的
1. HDMI CEC算是一个相当庞大的系统,想了解还要从HDMI接口信号啊.物理地址啊.逻辑地址啊等等HDMI基础的东西说起. 2. 不过可以简单的这么理解,在HDMI CEC最小系统里,所有通过H ...
- 使用eclipse和maven生成java web程序war包
一.eclipse中,在需要打包的项目名上右击,然后把鼠标光标指向弹出框中的“run as”: 二.之后会看到在这个弹出框的右侧会出现一个悬浮窗,如下: 三.在上边的第二个悬浮窗鼠标点击“maven ...
- Eclipse中Maven+Spring3.2.8+SpringMVC HelloWorld项目
本文适合有一定spring和springmvc基础,并想使用Maven管理项目的人. 源码打包:http://pan.baidu.com/s/1hqurUcs 转载请声明出处(http://www.c ...
- GR&R
ANOVA gauge R&R (or ANOVA gauge repeatability and reproducibility) is a measurement systems anal ...
- Tomcat远程调试catalina.sh的配置
#!/bin/sh # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license ...
- Shell_Oracle Erp和其他系统Interface资料传输通过Shell进行控制(案例)
2014-06-26 Created By BaoXinjian