我写了一个在生产者-消费者模型中使用 SynchronousQueue 的测试示例。但效果不好。以下是我的代码:
public class QueueTest {
String input;
int pos;
BlockingQueue<String> queue;
volatile boolean exitFlag;
QueueTest()
{
for(int i=0; i<10000; i++)
input += "abcde";
input += "X";
pos = 0;
queue = new SynchronousQueue<String>();
exitFlag = false;
}
public static void main(String[] args) {
QueueTest qtest = new QueueTest();
qtest.runTest();
}
void runTest()
{
Thread producer = new Thread( new Producer());
Thread consumer = new Thread( new Consumer());
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class Producer implements Runnable
{
public void run()
{
while(true)
{
String s = read();
if(s.equals("X"))
break;
try {
queue.put(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
exitFlag = true;
}
}
class Consumer implements Runnable
{
public void run()
{
while(exitFlag == false)
{
String s = null;
try {
s = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
process(s);
}
}
}
String read()
{
String str = input.substring(pos, pos+1);
pos++;
return str;
}
void process(String s)
{
long sum = 0;
for(long i=0; i<1000; i++)
sum = sum * i + i;
}
}
问题是运行像死锁一样卡住了。这些简单的代码中是否有任何错误?