Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads affected by Thread.yield()?

Here is a multi-threaded HelloWorld:

public class HelloWorld {

    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread() {
            public void run() {
                System.out.println("Hello World from new thread");
            }
        };
        myThread.start();
        Thread.yield();
        System.out.println("Hello from main thread");
        myThread.join();
    }
}

As I understand, after the myThread.start(), there will be two threads running. One is the main thread, and the other is the newly-created myThread. Then, which thread is referred to in the Thread.yield()?

I checked the Java SE6 Doc, which says

Thread.yield(): Causes the currently executing thread object to temporarily pause and allow other threads to execute

But in the codes, I can't see clearly what the currently excuting thread is, it looks that both threads are running at the same time.

Isn't it be more clear to say myThread.yield() instead of Thread.yield()? Does anyone have ideas about this?

like image 663
Hanfei Sun Avatar asked Nov 30 '25 12:11

Hanfei Sun


2 Answers

With "current thread" in this context, the Javadoc means "the thread that called the method Thread.yield()"

In your case, this is the main thread that started your application.

As the Javadoc explains, there is normally no need to call Thread.yield(). It's not required to do anything:

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

It does seem to do something, at least up to Java 6 - couldn't find a reference for Java 7/8.

Windows:

The Hotspot VM now implements Thread.yield() using the Windows SwitchToThread() API call. This call makes the current thread give up its current timeslice, but not its entire quantum.

Linux:

Under Linux, Hotspot simply calls sched_yield(). The consequences of this call are a little different, and possibly more severe than under Windows.

Source: http://www.javamex.com/tutorials/threads/yield.shtml

like image 122
Erwin Bolwidt Avatar answered Dec 02 '25 01:12

Erwin Bolwidt


The current thread is affected, i.e. the thread that calls the method.

Isn't it be more clear to say myThread.yield() instead of Thread.yield()? Does anyone have ideas about this?

No it isn't. It's a static method, and it's well-specified. In this case it would also convey the opposite of what actually happens.

But it's also pointless. yield() functions haven't done anything useful since the 16-bit part of Windows 98. Your thread will get rescheduled anyway as the scheduler sees fit.

like image 27
user207421 Avatar answered Dec 02 '25 01:12

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!