简体   繁体   English

关闭后Java线程暂停

[英]Java thread halting after shutdown

I've managed to configure a synchronised startup for my application, and I'm not implementing the shutdown.我已经设法为我的应用程序配置了同步启动,但我没有实现关闭。

I'm using a CountDownLatch to await the closure of all of my threads.我正在使用CountDownLatch来等待我所有线程的关闭。 Each thread loops until a ( volatile ) boolean, running , flag is set to false.每个线程都会循环,直到 ( volatile ) boolean, running , flag 设置为 false。

Here's an example ( Caught ) Runnable being ran on a thread这是一个在线程上运行的示例 ( Caught ) Runnable

System.out.println("STARTING");
startupLatch.countDown();
final BufferedReader reader = getReader();
String line;
System.out.println("STARTED");
while (running) {
    System.out.println("WAITING FOR CLOSE");
    while ((line = reader.readLine()) != null) {
        System.out.println("WAITING FOR NO MORE LINES");
        System.out.println(line);
    }
}
shutdownLatch.countDown();
System.out.println("EXITED READING THREAD: EXITS LEFT: " + shutdownLatch.getCount());

Initially I thought that the change to the running flag may not have been propogated to the thread, but it turns out that the thread is actually being blocked somewhere after reader.readLine() - thus the next iteration of the while loop can't be reached, where the shutdownLatch would be decremented.最初我认为对运行标志的更改可能没有传播到线程,但事实证明该线程实际上在reader.readLine()之后的某处被阻塞 - 因此 while 循环的下一次迭代不能达到, shutdownLatch将减少。

My console output is:我的控制台输出是:

STARTING开始

STARTED开始

WAITING FOR CLOSE等待关闭

SHUTTING DOWN关闭

SHUTTING DOWN come's from my close (shutdown) method. SHUTTING DOWN来自我的close (关闭)方法。

This loop was a while(true) loop before I decided to implement the orderly shutdown;在我决定实现有序关闭之前,这个循环是一个while(true)循环; so, a blocking readline call would be fine - actually preferable to spinning off while loop iterations - because this is on another thread.因此,阻塞readline调用会很好——实际上比在循环迭代时旋转更可取——因为这是在另一个线程上。 However, it seem's now I need to spin off while loops in order to figure out when the shut down occurs.但是,现在我似乎需要关闭 while 循环,以便确定何时发生关闭。

  • Is readline the issue here? readline是这里的问题吗? if so:如果是这样的话:
    • Is readline supposed to be blocking? readline应该阻塞吗?
    • How can I get around a blocking ?我怎样才能绕过阻塞?

使用reader.ready()检查下一次调用readLine()是否会阻塞当前线程

You can have non bocking IO only on sockets.您只能在套接字上使用非阻塞 IO。 To interrupt disk operation or any other IO of a Reader the Reader thread should be interrupted.要中断 Reader 的磁盘操作或任何其他 IO,应该中断 Reader 线程。 In the most cases you will get InterruptedIOException , which will break the loop.在大多数情况下,您会得到InterruptedIOException ,这将打破循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM