下面这个程序好奇怪啊,我是用信号量来实现生产者和消费者得同步的,在逻辑上是没有问题的,单步调试也没有异常抛出,但为什么直接运行会有错误呢?源代码如下:import java.util.ArrayList;
import java.util.concurrent.Semaphore;public class Buffer2 
{
private Semaphore empty = new Semaphore(10);
private Semaphore full = new Semaphore(0);
private ArrayList<Integer> arrayList = new ArrayList<Integer>(10);

public void set(int i) throws InterruptedException
{
empty.acquire();
arrayList.add(new Integer(i));
full.release();
}

public int get() throws InterruptedException
{
full.acquire();
int t = arrayList.remove(0).intValue();
empty.release();
return t;
}
}
public class Consumer implements Runnable
{
private Buffer2 buffer;
private int times;

public Consumer(Buffer2 buffer, int times)
{
this.buffer = buffer;
this.times = times;
}

public void run()
{
try
{
for (int i = 0; i < times; i++)
buffer.get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Producer implements Runnable 
{
private Buffer2 buffer;
private int times;

public Producer(Buffer2 buffer, int times)
{
this.buffer = buffer;
this.times = times;
}

public void run()
{
try
{
for (int i = 0; i < times; i++)
buffer.set(i);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Main 
{
public static void main(String[] args) throws InterruptedException
{
long past = System.currentTimeMillis();
Buffer2 buffer = new Buffer2();
Thread produce = new Thread(new Producer(buffer, 100));
Thread consume = new Thread(new Consumer(buffer, 100));
produce.start();
consume.start();
produce.join();
consume.join();
System.out.println(System.currentTimeMillis() - past);
}
}
错误信息如下:Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at Buffer2.get(Buffer2.java:21)
at Consumer.run(Consumer.java:18)
at java.lang.Thread.run(Unknown Source)

解决方案 »

  1.   

    貌似错误信息还不唯一,除了上面一种错误信息外,还有Exception in thread "Thread-1" java.lang.NullPointerException
    at Buffer2.get(Buffer2.java:21)
    at Consumer.run(Consumer.java:18)
    at java.lang.Thread.run(Unknown Source)
    但有时候却又能成功运行(概率极小),这是什么情况?
      

  2.   

    我在ibm dw网站看到的是使用 BlockingQueue