Java Threads: Thread scheduling-hibernation

Source: Internet
Author: User

The point here is to be clear, no matter how programmers write scheduling, can only maximize the impact of thread execution order, but not accurate control.

The purpose of thread hibernation is one of the easiest ways for a thread to give up the CPU, when the thread sleeps, it gives the CPU resources to other threads so that it can rotate, and when it sleeps for a certain time, the line Cheng wakes up and waits for execution.

The method of thread hibernation is thread.sleep (long Millis) and Thread.Sleep (long millis, int nanos), all static methods, which thread that calls sleep hibernation? Simply put, which thread calls sleep, sleeps which thread.

/**
* java thread: Thread scheduling-Hibernate
*
* @author leizhimin
*/
public class Test {
public static                  void Main (string[] args) {
Thread t1 = new MyThread1 ();
Thread t2 = new Thread (new myrunnable ());
T1.start ();
T2.start (); 
}
}
Class MyThread1 extends Thread {
public void run () {
for int i = 0; I < 3; i++) {
System.out.println ("Thread 1" + i + "secondary execution!") ");                         
try {
Thread.Sleep;
                         catch (Interruptedexception e) {
E.printstacktrace ();

}
}
}
Class Myrunnable implements Runnable {
public void run () {
for (int i = 0; i < 3; i++) {
System.out. println ("Thread 2" + i + "secondary execution!") ");                         
try {
Thread.Sleep;
                         catch (Interruptedexception e) {
E.printstacktrace ();

}
}
}

线程2第0次执行!
线程1第0次执行!
线程1第1次执行!
线程2第1次执行!
线程1第2次执行!
线程2第2次执行!
Process finished with exit code 0

From the results above, it can be seen that the thread execution order cannot be guaranteed accurately.

Source: http://lavasoft.blog.51cto.com/62575/221790

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.