简体   繁体   English

从套接字流中读取时是否需要线程休眠?

[英]Is thread sleep necessary when reading from a socket stream?

I am reading from a socket input stream like this 我正在从这样的套接字输入流中读取

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;

while((line = in.readLine()) != null){
   // do something
   Thread.sleep(10); // for example 10ms
}

Now, the read method of an input stream blocks until data is available. 现在, 输入流的读取方法将阻塞,直到有可用数据为止。

In this case is cooling-down the thread a good idea? 在这种情况下, 冷却线程是个好主意吗? After 10ms it will be blocking anyway. 10ms之后,它将始终处于阻塞状态。

Please do not tell me about non-blocking IO, I know about that. 请不要告诉我有关非阻塞IO的信息,我知道这一点。

I am just curious whether it helps performance/CPU in anyway. 我只是很好奇它是否无论如何都有助于提高性能/ CPU。

No . 不行 There's no reason to sleep. 没有理由睡觉。 Why artificially slow down the read loop? 为什么人为地减慢读取循环? Let it read data as fast as it comes in. 让它以最快的速度读取数据。

If you want to let other threads a cpu time, you should use: 如果要让其他线程占用CPU时间,则应使用:

Thread.yield();

But I'm not think it's necessary here- let the system thread scheduling do its job- it's pretty good. 但是我认为这里没有必要-让系统线程调度完成工作-很好。

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

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