java多线程之生产者消费者经典问题
来源:互联网 发布:ubuntu owncloud 编辑:程序博客网 时间:2024/04/30 06:33
package com.thread;/** * 此程序不仅可以加深对多线程的理解,并且可以加深对面向对象编程的理解 * 此程序并非是一个很完善的程序,阅读代码的过程中要发现发生死锁的原因以及找到解决问题的方法 * * cehkongfu:2015.1.28 */class Factory {private int i = 0;private boolean created = false;public void create() {synchronized (this) {if (created) {try {wait();} catch (InterruptedException e) {}} else {i = i + 1;System.out.println(Thread.currentThread().getName() + "-create-" + i);notify();this.created = true;}}}public void consume() {synchronized (this) {if (created) {System.out.println(Thread.currentThread().getName() + "-consume-" + i);notify();this.created = false;} else {try {wait();} catch (InterruptedException e) {}}}}}abstract class AbsFactory implements Runnable {protected Factory factory = null;public AbsFactory(Factory factory) {this.factory = factory;}abstract protected void execute();public void run() {while (true) {execute();try {Thread.sleep(10);} catch (InterruptedException e) {}}}}class Producer extends AbsFactory {public Producer(Factory factory) {super(factory);}@Overrideprotected void execute() {factory.create();}}class Consumer extends AbsFactory {public Consumer(Factory factory) {super(factory);}@Overrideprotected void execute() {factory.consume();}}public class ProducerCustomer {public static void main(String[] args) {if (args.length == 0) {System.out .println("Usage:java com.wenhuisoft.chapter4.ProducerCustomer number");System.out.println("Please restart again....");System.exit(0);}int count = 0;try {count = Integer.parseInt(args[0]);} catch (Throwable t) {System.out.println("Please enter a integer type number...");System.exit(0);}final Factory factory = new Factory();for (int i = 0; i < count; i++) {new Thread(new Producer(factory)).start();new Thread(new Consumer(factory)).start();}}}
0 0
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- java多线程之生产者消费者经典问题
- 多线程经典问题之生产者消费者问题的JAVA实现
- java多线程之生产者和消费者经典问题案例
- 多线程之经典生产者消费者问题
- java多线程-生产者消费者经典问题
- java多线程经典的生产者消费者问题
- Java经典多线程问题--生产者与消费者
- java多线程之生产者消费者问题
- java基础:多线程之生产者消费者问题
- inet_ntoa(), inet_aton(), inet_addr
- 如何解决Android SDK中离线文档打开慢的问题
- 如何去掉UISearchBar背景框?
- UVa-Beginning Algorithm Contests
- SGU 390 Tickets(数位DP)
- java多线程之生产者消费者经典问题
- java 操作 vsftp 文件
- 什么是哈希码?
- SSH框架总结(框架分析+环境搭建+实例源码下载)
- initrd.img中的init脚本分析,load_modules()分析
- 【设计模式学习笔记十二】【结构型模式】【享元模式(FlyWeight)】
- UVa 1592 Database ACM解题报告(map和pair的使用)
- APP将会灭亡?
- 每一个程序员需要了解的10个Linux命令