>我正在使用弹簧引导
public interface StringConsume extends Consumer<String> {
default public void strHandel(String str) {
accept(str);
}
}
英普尔
@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 循环吗?假设调用了5 次 StringConsumeImpl 类,那么 do while 循环将创建 5 个进程或仅创建 1 个进程? 以及 StringConsumptionImpl 中 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
所示)。