Java实现同步机制(生产者消费者)
2012-09-23 12:33
441 查看
Java实现线程的同步,可以通过synchronized,wait(), notitfy(), notifyAll();假设一个线程(生产者)生产产品,一个线程(消费者)消费产品,其访问的资源时间都是随机的,这样就是生产者必须得产品(资源)消费完成之后才可以生产,而消费者必须在产品有的时候才可以消费,这就是必须对资源进行同步操作,对资源的使用部分的代码需要加入锁。
下列是我的实现方法:
下列是我的实现方法:
package com.lzb.common; import java.util.Random; import java.util.concurrent.TimeUnit; /** * * 功能描述:生产者消费者 * 注:锁synhronized是放在“资源的类的内部方法中”,而不是在线程的代码中 */ public class ProducterCustomer { private PCResource pc = new PCResource(); // 生产者与消费者调用的时间随机 private Random rand = new Random(50); public void init() { // 生产者 new Thread(new Runnable(){ public void run() { while(true) { pc.producter(); try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}).start(); // 消费者 new Thread(new Runnable(){ public void run() { while(true) { pc.customer(); try { TimeUnit.MILLISECONDS.sleep(rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}).start(); } public static void main(String[] args) { ProducterCustomer startPc = new ProducterCustomer(); startPc.init(); } } /** * * 功能描述:同步资源 * */ class PCResource { private static final Integer MAX = 1; private static final Integer MIN = 0; private int product = 0; // 同步互斥通信标志 private boolean isRunning = true; /** * * 功能描述:生产产品,当生产一个商品后挂起,等待消费者消费完成 */ public synchronized void producter() { while(isRunning) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } product++; System.out.println("-------->Product " + product + " good"); if(product >= MAX) break; } isRunning = false; notify(); } /** * * 功能描述:消费者,消费产品,当产品为0时,等待生产者生产产品 */ public synchronized void customer() { while(!isRunning) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } product--; System.out.println("Limit " + product + " goods<----------"); if(product <= MIN) { break; } } isRunning = true; notify(); } }
相关文章推荐
- 基于Java自带同步机制实现生产者-消费者模式
- Java实现同步机制(生产者消费者)
- Java实现同步机制(生产者消费者)
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- Java实现生产者与消费者(四)(多生产者与多消费者使用lock同步锁)
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- java同步和互斥的应用:生产者消费者之爸爸妈妈儿子女儿苹果橘子编程实现
- Java多线程 多个生产者和多个消费者实现同步 jdk1.5
- 基于并发包同步机制实现生产者-消费者模式
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现
- 关于网宿厦门研发中心笔试的一道PV操作题:利用java中的多线程实现生产者与消费者的同步问题
- java多线程实现生产者/消费者同步
- java基础复习之二:Java实现同步机制是(生产消费者)
- Java实现生产者与消费者的同步
- Java线程间同步实现生产者-消费者模式
- Java多线程 多个生产者和多个消费者实现同步 jdk1.4
- 进程同步-生产者和消费者(PV操作实现——java多线程模拟)
- 多生产者--多消费者 显示锁实现同步 java实现
- Java Note: 多线程的同步(互斥锁)的方法对比,信号量锁,读写锁的实现,生产者-消费者模式的实现