我正在运行一个具有业务服务的SpringBoot应用程序,它不断地触发一个方法,该方法用它的消息填充一个全局队列。在此方法中,由于每秒触发的次数超过15-30次,该方法检查布尔值的全局数组,以确保没有启动特定索引的线程(0-7)。如果线程未启动,则该方法将触发该线程。每个线程负责读取消息的全局队列,并对此消息执行任务。但是,我注意到,随着应用程序运行时间的延长,我只看到其中一个线程运行该操作,而其他线程则被卡住了。
我的问题是,如果我有:
public static void onMessage(String record) {
global.add(record);
if(threads[0] == false) {
threads[0] = true;
thread0.start() // Name of the thread index included in runnable
> }基本上,上面的内容是不断触发的,填充队列,尝试启动线程,就是这样。
那我就有:
public void run() {
String recordToUse;
int thread_num = Integer.parseInt(Thread.currentThread().getName());
long startThreadTime = System.currentTimeMillis();
long endThreadTime = startThreadTime + 60 * 1000; // Run the thread for 1 minute.
while(System.currentTimeMillis() < endThreadTime) {
if(!global.isEmpty()) {
recordToUse = global.remove();
System.out.println("Successful removal: Thread-"+ thread_num);
} else {
continue; // If the queue is empty, keep checking until it is not empty.
}
// Then we have more operations that work on the message
}
threads[thread_num] = false; // Mark that this thread is now finished and the onMessage method knows it can start another thread.
return;
}runnable实现将一个数字作为参数来存储线程中的线程数,因此我们有类似于Thread thread1 = new (runnable,"0");,以便上面的线程知道它是数字0索引。
在应用程序按预期运行之后,我首先看到,在8个预期线程中,最初运行良好,并显示如下消息:
Successful removal: Thread-2
Successful removal: Thread-0
Successful removal: Thread-5
Successful removal: Thread-7
Successful removal: Thread-4
Successful removal: Thread-1但是在大约5-10分钟之后,它将重点放在一个单个线程上。我只看到这样的信息:
Successful removal: Thread-6
Successful removal: Thread-6
Successful removal: Thread-6
Successful removal: Thread-6
Successful removal: Thread-6
Successful removal: Thread-6我不太清楚发生了什么,一些指导将是伟大的!我的想法是线程正在访问一个同步方法,而其他线程都在等待它,但我不确定是否会这样,因为它们最初都在工作。
谢谢。
我一直试图在这里和那里休眠线程,我一直在玩线程的继续部分,但是我看不到这些线程被卡在哪里。
发布于 2022-11-20 16:28:40
java.util.concurrent.BlockingQueue.)https://stackoverflow.com/questions/74392204
复制相似问题