import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class TestPC { List listFactory = new ArrayList();
private final TimeUnit TimeUnitMILLISECONDS = null;
private Lock lock = new ReentrantLock();
private Condition sufficientFunds = lock.newCondition(); public static void main(String[] args) {
TestPC tpc = new TestPC();
tpc.start();
} public void start() {
new ProducterThread1().start();
new ConsumerThread1().start();
} class Producter1 {
/**
 * 产生随机字符串
 * 
 * @param lengthOfString
 * @return
 */
public void productString(int lengthOfString) {
lock.lock();
try {
sufficientFunds.await(1000, TimeUnit.MILLISECONDS);
String radStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuffer result = new StringBuffer();
Random rand = new Random();
for (int i = 0; i < lengthOfString; i++) {
int randNum = rand.nextInt(36);
result.append(radStr.substring(randNum, randNum + 1));
}
String productResult = result.toString();
System.out.println("生产者" + productResult);
TestPC.this.listFactory.add(productResult);
sufficientFunds.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
} } class ProducterThread1 extends Thread {
Producter p = new Producter(); public void run() {
while (true) {
//System.out.println(Thread.currentThread().getName());
p.productString(2);
// p.getString();
}
}
} class Consumer {
/**
 * 获取随机字符串
 */
public void getString() {
lock.lock();
try {
sufficientFunds.await(2000, TimeUnit.MILLISECONDS);
int index = 0;
String getResultStr = "";
getResultStr = (String) TestPC.this.listFactory.get(index);
System.out.println("消费者获取的" + getResultStr);
TestPC.this.listFactory.remove(index);
sufficientFunds.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
} class ConsumerThread1 extends Thread {
Consumer c = new Consumer(); public void run() {
while (true) {
c.getString();
}
} }
}哪位高手帮我看下为什么执行不了 Consumer的线程???提示数组越界了!!

解决方案 »

  1.   

    没有问题啊结果
    生产者QY
    消费者获取的QY
    生产者FR
    消费者获取的FR
    生产者IJ
    消费者获取的IJ
    生产者PN
    消费者获取的PN
    生产者57
    消费者获取的57
    生产者I8
    消费者获取的I8
    生产者85
    消费者获取的85
    生产者YV
    消费者获取的YV
    ....
      

  2.   


    我在我电脑上运行的:
    生产者WI
    生产者94
    生产者3F
    生产者SG
    生产者Y9
    生产者88
    生产者35
    ...