yz454170989
yz454170989
2015-07-07 01:36

java关于线程同步的问题

5
  • java
  • 线程

package 线程.TestTeread_5;

/*
push和pop增加减少数组元素,
我的问题是:
为什么去掉push和pop的synchronized修饰关键词时,会报如下错误
异常:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at 线程.TestTeread_5.SynStack.push(TestTeread_5.java:19)
at 线程.TestTeread_5.Producer.run(TestTeread_5.java:57)
at java.lang.Thread.run(Unknown Source)

*/

class SynStack {//同步栈
private char [] data = new char [6];

private int cnt = 0;//cnt表示的是数组有效元素的个数

public synchronized void push(char val){
    while(cnt == data.length)
    {
        try
        {   
            this.wait();
            }
        catch(Exception e)
        {}

    }
    this.notify();
    data[cnt] = val;
    System.out.println("生产第"+cnt+"个产品,产品名为"+data[cnt]);
    cnt ++;
}
public synchronized char pop(){

    while(cnt == 0)
    {
        try
        {   
            this.wait();//暂停当前线程,转去执行另一个线程
            }
        catch(Exception e)
        {}
    }
    this.notify();
    char Key = data[cnt-1];
    System.out.println("消费第"+cnt+"个产品,产品名为"+Key);
    cnt --;
    return Key;
}

}

class Producer implements Runnable
{
private SynStack ss = null;
public Producer(SynStack ss)
{
this.ss = ss;
}
public void run()
{
char ch;
for(int i=0; i<20; i++)
{

        ch = (char)('a'+i);
        ss.push(ch);
    }

}

}

class Consumer implements Runnable{
private SynStack ss = null;
public Consumer (SynStack ss)
{
this.ss = ss;
}
public void run()
{

    //ss.pop(); 
    for(int i=0; i<20; i++)
    {
        ss.pop();
    }

}

}
public class TestTeread_5 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SynStack ss =new SynStack();
    Producer pp = new Producer(ss);
    Consumer cc = new Consumer(ss);

    Thread t1 = new Thread(pp);
    t1.start();
    Thread t2 = new Thread(cc);
    t2.start();
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

5条回答

为你推荐

换一换