Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Question about Thread.yield()

807597Feb 22 2005 — edited Feb 22 2005
In my IM application I have two threads: one is for receiving and second for sending messages. Both threads use an object which is queue. Receiving thread always scan the queue checking for new messages. To avoid 100% CPU load I use sleep(100) method:
class RecvThread extends Thread {
    /* Only this method is displayed, but has more methods */
    public void run() {
        while (fRunThread) { /* fRunThread declared as boolean */
            try {
                sleep(100);
                synchronized (pq) {
                    packet = pq.pull();
                }
                if (null == packet) {
                    continue;
                }
                notifyPacketHandlers(packet);
            } catch (InterruptedException ex) {
            }
        }
    }
}
Later I found yield() method. Will that yield() method work same like sleep(100) in my case? I.e. if I will use the code
class RecvThread extends Thread {
    /* Only this method is displayed, but has more methods */
    public void run() {
        while (fRunThread) { /* fRunThread declared as boolean */
            yield();
            synchronized (pq) {
                packet = pq.pull();
            }
            if (null == packet) {
                continue;
            }
            notifyPacketHandlers(packet);
        }
    }
}
will it work same like the previous?
Thank you.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 22 2005
Added on Feb 22 2005
8 comments
245 views