编写程序,实现生产者和消费者问题。输入:由英文字母和数字组成的不定长度字符串数组,例如{“abc”,”23d”,”1a”}。每隔100毫秒,生产者线程读入数据,放入生产者公用的仓库;消费者从仓库中取出字符串,进行倒置,如上例{“cba”,”d32”,”a1”}; 输出:倒置后的字符串。
package bounded.buffer.problem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.*;
public class Main {
private static final BlockingDeque<String> stringBlockingDeque = new LinkedBlockingDeque<>();
private static final ArrayList<String> strings = new ArrayList<>();
private static Integer index = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
strings.addAll(Arrays.asList(scanner.nextLine().split(" ")));
Producer producer = new Producer();
Consumer consumer = new Consumer();
ExecutorService service = Executors.newCachedThreadPool();
service.execute(producer);
service.execute(consumer);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
service.shutdown();
}
static class Producer implements Runnable{
@Override
public void run() {
while (index < strings.size()) {
try {
stringBlockingDeque.put(strings.get(index));
System.out.println(Thread.currentThread().getName() + " : Producer put " + strings.get(index++));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable{
@Override
public void run() {
while (true) {
if (index >= strings.size()) {
break;
}
try {
System.out.println(Thread.currentThread().getName() + " : Consumer get " + new StringBuffer(stringBlockingDeque.take()).reverse());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}