Why is threading works on a single core CPU?

牧云@^-^@ 提交于 2019-12-05 18:47:27

The result is 5, not 6, because the two threads can sleep simultaneously. Going to sleep by calling Thread.sleep() lets the other thread run, but the remaining sleep interval timer continues ticking for both threads.

Note that this applies only to sleeping (which uses nearly zero CPU), but not to doing useful work: in this case the timing on a single-core non-hyperthreaded CPU would indeed be additive. For example, if one thread needed to do five seconds worth of number crunching, and the other needed to do a second worth of number crunching, the total time for both threads would be six seconds.

By calling Thread.sleep(sleeptime), the Thread signals that it doesn't need the CPU for at least 'sleeptime' millis.

In the meantime the other thread can be executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!