线程 --生产和消费问题
来源:互联网 发布:java 初始化错误异常 编辑:程序博客网 时间:2024/05/06 05:39
package com.lan;
/**
* 生产和消费的问题
* @ClassName: ProducerConsumer
* @Description: TODO
* @author LanHantong
* @date 2011-8-9 下午03:13:39
*
*/
public class ProducerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
//窝头类
class WoTou{
}
//箩筐类
class SyncStack{
//唤醒其他线程
this.notify();
arrWT[index] = wt;
index++;
}
//消费方法
public synchronized WoTou pop(){
this.notify();
index--;
return arrWT[index];
}
}
//生产线程
class Producer implements Runnable{
}
//消费线程
class Consumer implements Runnable{
}
/**
* 生产和消费的问题
* @ClassName: ProducerConsumer
* @Description: TODO
* @author LanHantong
* @date 2011-8-9 下午03:13:39
*
*/
public class ProducerConsumer {
/**
* @param args
*/
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}//窝头类
class WoTou{
int id;
WoTou(int id){
this.id = id;}
public String toString(){
return "wotou :" + id;
}
}
//箩筐类
class SyncStack{
int index = 0;
WoTou[] arrWT = new WoTou[6];
//生产方法
public synchronized void push(WoTou wt){
while(index == arrWT.length ){
try {
//等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}}
//唤醒其他线程
this.notify();
arrWT[index] = wt;
index++;
}
//消费方法
public synchronized WoTou pop(){
while(index == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}}
this.notify();
index--;
return arrWT[index];
}
}
//生产线程
class Producer implements Runnable{
SyncStack ss = null;
//构造方法 持有SyncStack的引用
Producer(SyncStack ss){
this.ss = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<20; i++){
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了,"+wt);
try {
Thread.sleep((int)(Math.random()*200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
}
//消费线程
class Consumer implements Runnable{
SyncStack ss = null;
//构造方法 持有SyncStack的引用
Consumer(SyncStack ss){
this.ss = ss;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<20; i++){
WoTou wt = ss.pop();
System.out.println("消费了,"+wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 线程 --生产和消费问题
- 线程---生产消费问题
- java学习9:生产和消费问题,先生产才能消费,线程间通信与等待
- 【Java】----线程同步:生产-消费问题
- Java 线程同步 生产消费问题
- 8.05(生产和消费线程)
- 多线程经典问题:馒头问题 生产和消费问题(线程的通信问题)
- 线程生产消费模式
- 线程间通信:生产线程和消费线程
- 进程同步实例--消费和生产问题
- 多线程生产消费问题
- 生产消费问题
- java生产消费问题
- 经典的生产与消费线程同步问题
- 生产和消费
- 继 生产和消费
- 消费和生产 二条线程同步 的例子
- Java多线程的单生产单消费和多生产多消费问题的解决
- const的常见用法
- 武侠世界,基于Ogre的地形分析
- IE8不能居中显示的5个解决办法
- C#转义字符
- 静态内存;堆内存;函数局部栈内存 demo程序(摘自C++程序员求职关键路径)
- 线程 --生产和消费问题
- cocos2d制作的塔防游戏(一)(共五篇)
- SIFT特征匹配中的相关问题
- 给电脑的情人节礼物
- 让iframe简单有效自适应高度
- hdu2066
- 用策略屏蔽135 139 445 3389端口+网络端口安全防护技 .
- flex与java的一种通信方式
- [Java] 自动生成visual studio项目文件