我正在使用弹簧靴
public interface StringConsume extends Consumer<String> {
default public void strHandel(String str) {
accept(str);
}
}
Impl
@Component("StrImpl")
public class StringConsumeImpl implements StringConsume {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(500);
final ExecutorService exService = Executors.newSingleThreadExecutor();
Future<?> future = CompletableFuture.completedFuture(true);
@Override
public void accept(String t) {
try {
queue.put(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (null != queue.peek()) {
if (future.isDone()) {
future = exService.submit(() -> queue.take());
}
}
}
}
类
@Component
public class Test {
@Resource(name="StrImpl")
private @Autowired StringConsume handler;
public void insertIntoQueue(String str) {
handler.accept(str);
}
}
在StringConsumeImpl中,是否需要同步while循环?并假设调用了五个时间StringConsumeImpl类,那么while循环会创建5个进程还是仅创建1个进程?以及StringConsumeImpl中while循环的最佳替代方法是什么?
最佳答案
该代码存在一些问题。
首先,使用者并没有真正“消费”任何东西,它只是将字符串添加到队列中,然后将其取出。出于争论的目的,我们说它也通过打印到控制台或其他东西来“消耗”它。
其次,由于循环,使用者只会被调用一次,除非它在自己的线程中运行。例如,如果您这样做
public static void main(String[]args) {
StringConsume consumer = new StringConsumeImpl();
consumer.accept("hello");
}
使用者将“ hello”放入队列,立即将其取出,然后停留在循环中,等待更多元素取出。但是,没有人可以实际添加任何内容。
做您想做的事情的通常概念是“生产者/消费者”。这意味着有一个“生产者”将项目放入队列中,还有一个“消费者”将它们取出并用它们进行处理。
因此,在您的情况下,您的类要做的是通过将字符串放入队列中来“使用”该字符串,使其成为“生产者”,然后通过将其从队列中取出来“使用”该字符串。当然,也有字符串的“实际”生成器,即调用该类的类。
因此,通常您会执行以下操作:
/** Produces random Strings */
class RandomStringProducer {
Random random = new Random();
public String produceString() {
return Double.toString(random.nextDouble());
}
}
/** Prints a String */
class PrintConsumer implements StringConsume {
public void accept(String s) { System.out.println(s); }
}
/** Consumes String by putting it into a queue */
class QueueProducer implements StringConsume {
BlockingQueue<String> queue;
public QueueProducer(BlockingQueue<String> q) { queue = q; }
public void accept(String s) {
queue.put(s);
}
}
public static void main(String[] args) {
// the producer
RandomStringProducer producer = new RandomStringProducer();
// the end consumer
StringConsume printConsumer = new PrintConsumer();
// the queue that links producer and consumer
BlockingQueue<String> queue = new ArrayBlockingQueue<>();
// the consumer putting strings into the queue
QueueProducer queuePutter = new QueueProducer(queue);
// now, let's tie them together
// one thread to produce strings and put them into the queue
ScheduledExecutorService producerService = Executors.newScheduledThreadPool(1);
Runnable createStringAndPutIntoQueue = () -> {
String created = producer.createString();
queuePutter.consume(created);
};
// put string into queue every 100ms
producerService.scheduleAtFixedRate(createStringAndPutIntoQueue, 100, TimeUnit.MILLISECONDS);
// one thread to consume strings
Runnable takeStringFromQueueAndPrint = () -> {
while(true) {
String takenFromQueue = queue.take(); // this will block until a string is available
printConsumer.consume(takenFromQueue);
}
};
// let it run in a different thread
ExecutorService consumerService = Executors.newSingleThreadExecutor();
consumerService.submit(takeStringFromQueueAndPrint);
// this will be printed; we are in the main thread and code is still being executed
System.out.println("the produce/consume has started");
}
因此,运行此线程时,将有三个线程:主线程,生产者线程和使用者线程。生产者和消费者将同时执行其操作,并且主线程也将继续运行(如最后一行中的
System.out.println
所示)。