Usage of yield () in Java threads

Source: Internet
Author: User

The Thread.yield () method acts: Pauses the currently executing thread and executes other threads. (may not be effective)

Yield () gives the currently running thread back to the operational state to allow other threads with the same priority to get the chance to run. Therefore, the purpose of using yield () is to allow the appropriate rotation between threads with the same priority to execute . However, in practice there is no guarantee that yield () can achieve the purpose of concession, because the thread that withdraws may be checked again by the thread scheduler.

Conclusion: In most cases, yield () will cause the thread to go from the running state to the operational state, but it may not be effective.

public class Testyield {
public static void Main (String [] args) {
MyThread T1 = new MyThread ("T1");
MyThread t2 = new MyThread ("T2");
T1.start ();
T2.start ();
}
}

Class MyThread extends thread{
MyThread (String s) {
Super (s);
}

public void Run () {
for (int i = 0; I <=; i + +) {
System.out.println (GetName () + ":" +i);
if (("T1"). Equals (GetName ())) {
if (i = = 0) {
Yield ();
}
}
}
}

}

The result of the operation is variable.

Usage of yield () in Java threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.