题目
编写程序,实现生产者和消费者问题。输入:由英文字母和数字组成的不定长度字符串数组,例如{“abc”,”23d”,”1a”}。每隔100毫秒,生产者线程读入数据,放入生产者公用的仓库;消费者从仓库中取出字符串,进行倒置,如上例{“cba”,”d32”,”a1”}; 输出:倒置后的字符串。
代码
package Homework05;
import java.util.concurrent.*;
public class PV {
public static void main(String[] args) {
BlockingQueue<String>q=new ArrayBlockingQueue<String>(1);
String []s=new String[] {"abc1","c2","5h3","0u4","3rg5"};
Thread P=new Thread(new Producer(q,s));
Thread C=new Thread(new Consumer(q));
P.start();
C.start();
}
}
//生产者进程
class Producer implements Runnable
{
private BlockingQueue<String>q=null;
String []stringArray=new String[5];
public Producer(BlockingQueue<String>q,String[]stringArray)
{
this.q=q;
this.stringArray=stringArray;
}
public void run()
{
int i=0;
while(true)
{
try
{
String s=new String(stringArray[i]);
q.put(s);
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
i=(i+1)%5;
}
}
}
//消费者进程
class Consumer implements Runnable
{
private BlockingQueue<String>q=null;
public Consumer(BlockingQueue<String>q)
{
this.q=q;
}
public void run()
{
int i=0;
while(i<100)
{
try
{
StringBuffer reverseS=new StringBuffer(q.take());
reverseS.reverse();
System.out.println(Thread.currentThread().getName()+":"+reverseS);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
i++;
}
}
}