java关于多线程的问题?

[复制链接]
查看11 | 回复2 | 2011-10-30 11:56:50 | 显示全部楼层 |阅读模式
多线程题目场景:在果园里,有一个箱子,可以存放5个苹果,采摘者一直采摘苹果,并往箱子里放,购买者一直从箱子里拿走苹果。如果箱子里已经满5个苹果,则采摘者必须等待购买者至少拿走一个苹果后才能继续往箱子里放苹果。如果箱子里苹果没有了,则购买者必须等待采摘者往箱子里放苹果后才能拿走一个苹果。请使用多线程实现以上场景,请高手指点下
回复

使用道具 举报

千问 | 2011-10-30 11:56:50 | 显示全部楼层
给个例子给你参考一下!原理是一样的publicclassProCon{//测试//主方法publicstaticvoidmain(String[]args){SyncStackstack=newSyncStack();Consumerp=newConsumer(stack);Producerc=newProducer(stack);newThread(p).start();newThread(c).start();}}classProducerimplementsRunnable{//生产者privateSyncStackstack;publicProducer(SyncStackstack){this.stack=stack;}publicvoidrun(){for(inti=0;istack.pro().length;i){Stringproduct=\"产品\"i;stack.push(product);System.out.println(\"生产了:\"product);try{Thread.sleep(200);}catch(InterruptedExceptione){e.printStackTrace();}}}}classConsumerimplementsRunnable{//消费者privateSyncStackstack;publicConsumer(SyncStackstack){this.stack=stack;}publicvoidrun(){for(inti=0;istack.pro().length;i){Stringproduct=stack.pop();System.out.println(\"消费了:\"product);try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}}}}classSyncStack{//此类是(本质上:共同访问的)共享数据区域privateString[]str=newString[10];privateintindex;publicsynchronizedvoidpush(Stringsst){//供生产者调用if(index==sst.length()){try{wait();}catch(InterruptedExceptione){e.printStackTrace();}}this.notify();//唤醒在此对象监视器上等待的单个线程str[index]=sst;index;}publicsynchronizedStringpop(){//供消费者调用if(index==0){try{wait();}catch(InterruptedExceptione){e.printStackTrace();}}notify();index--;Stringproduct=str[index];returnproduct;}publicString[]pro(){//就是定义一个返回值为数组的方法,返回的是一个String[]引用returnstr;//这是一个String[]引用}}追问可以告诉我你的QQ吗?或者你加我也行:719699018我把我写的代码发给你看下,你帮我看看是哪里不对
回复

使用道具 举报

千问 | 2011-10-30 11:56:50 | 显示全部楼层
继承Thread和实现Runnable接口是一样的哇你提的问题就是关于生产者和消费者的问题的哇。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行