How to avoid busy spinning in Java

前端 未结 4 2167
南旧
南旧 2021-02-09 16:02

I have a multi-threaded application where a thread sends a message to another thread. The waiting thread polls for the message and reacts (locks are handled). Like this:

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 16:23

    You're doing busy waiting. You should never do that because it wastes CPU cycles. A thread or process waiting for some event should be in blocked state. Here are possible ways to achieve this:

    • Use Semaphores
    • Use synchronized methods with wait/notify
    • For specifically exchanging messages between threads, using BlockingQueues may be the best option

提交回复
热议问题