题目要求
编写程序,实现生产者和消费者问题。输入:由英文字母和数字组成的不定长度字符串数组,例如{“abc”,”23d”,”1a”}。每隔100毫秒,生产者线程读入数据,放入生产者公用的仓库;消费者从仓库中取出字符串,进行倒置,如上例{“cba”,”d32”,”a1”}; 输出:倒置后的字符串。
提示:可以定义4个类:生产者类、消费者类、产品类和测试类。
代码示例
class Production{
String [] strings;
private String aString;
private Boolean isconsumed=false;
public Production() {}
public Production(String [] s) {
strings = s;
}
public synchronized void produce(String s) {
if(!isconsumed) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
aString = s;
isconsumed = false;
notify();
}
public synchronized void consume() {
if(isconsumed) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(aString!=null) {
for(int i=aString.length()-1;i>=0;i--) {
System.out.print(aString.charAt(i));
}
System.out.println();
}
isconsumed=true;
notify();
}
}
class Producer implements Runnable{
private Production production;
public Producer(Production p) {
production = p;
}
@Override
public void run() {
int i=0;
while(true) {
try {
i=i%production.strings.length;
production.produce(production.strings[i]);
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
}
class Consumer implements Runnable{
private Production production;
public Consumer(Production p) {
production = p;
}
@Override
public void run() {
while(true) {
production.consume();
}
}
}
public class Main {
public static void main(String[] args) {
String [] strings={"abc","23d","1a"};
Production production = new Production(strings);
new Thread(new Producer(production)).start();
new Thread(new Consumer(production)).start();
}
}