浏览 1753 次
|
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
|---|---|
| 作者 | 正文 |
|
时间:2004-11-13
软件环境:
win2000+jdk 1.4.2 配置文件: 正常 错误提示信息: 输出显示让人费解 你的分析: class SyncStack{ private int index = 0; private char[] buffer = new char[6]; public synchronized void push(char c){//这里使用了void,意思表明没有返回值。 while(index == buffer.length){ try{ wait(); }catch(InterruptedException e){}//个人观点:notify();应放到这里。 } buffer[index]=c; index++; notify(); } public synchronized char pop(){//这是使用了char,意思表明要返回char类型 while(index ==0){ try{ wait(); }catch(InterruptedException e){}//个人观点:notify();应放到这里。 } notify(); index--; return buffer[index]; } }//SyncStack类结束 //Producer开始 class Producer implements Runnable{ SyncStack theStack; public Producer(SyncStack s){ theStack = s; } public void run(){ char c; for(int i=0;i<20;i++){ c=(char)(Math.random()*26+'A');//什么意思??? theStack.push(c); System.out.println("Produced:"+c); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){} } } } //Producer结束 //Consumer开始 class Consumer implements Runnable{ SyncStack theStack; public Consumer (SyncStack s){ theStack = s; } public void run(){ char c; for(int i=0;i<20;i++){ c=theStack.pop(); System.out.println("Consumed:"+c); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){} } } } //Consumer结束 public class SyncTest{ public static void main(String arguments[]){ SyncStack stack = new SyncStack(); Producer source = new Producer(stack); Consumer sink = new Consumer(stack); Thread t1 = new Thread(source); Thread t2 = new Thread(sink); t1.start(); t2.start(); } } 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
时间:2004-11-13
老师们都在争论啥呀?
|
|
| 返回顶楼 | |
|
时间:2004-11-14
看了那些问题,有点搞笑。
回去仔细看一下JDK再来发问! |
|
| 返回顶楼 | |
|
时间:2004-11-14
为什么不是生产在先,消费在后,有时顺序会错乱?如果你知道就说一下,没有必要取笑人家?
|
|
| 返回顶楼 | |
|
时间:2004-11-14
不是吧, 难道一个拉丁字母还没有生产出来就被消费了? 把你的运行结果贴出来看看.
生产者和消费者问题就是要演绎供不应求或供大于求的情况下程序怎么处理. 如果是生产在先, 消费在后就没有这个问题了. |
|
| 返回顶楼 | |
|
时间:2004-11-15
此图为我运行这个文件的结果:
|
|
| 返回顶楼 | |
|
时间:2004-11-15
是线程打印信息的优先顺序有问题,这样改改代码就清楚了:
[code:1] class SyncStack { private int index = 0; private char[] buffer = new char[6]; public synchronized void push(char c) {//这里使用了void,意思表明没有返回值。 while (index == buffer.length) { try { wait(); } catch (InterruptedException e) { }//个人观点:notify();应放到这里。 } buffer[index] = c; index++; System.out.println("push:" + c); notify(); } public synchronized char pop() {//这是使用了char,意思表明要返回char类型 while (index == 0) { try { wait(); } catch (InterruptedException e) { }//个人观点:notify();应放到这里。 } notify(); index--; char c = buffer[index]; System.out.println("pop:" + c); return c; } }//SyncStack类结束 [/code:1] 就清楚了[/code] |
|
| 返回顶楼 | |








