Java thread (7): Thread Scheduling-sleep

Source: Internet
Author: User

Java thread: Thread Scheduling-sleep Java thread scheduling is the core of Java multithreading. Only good scheduling can give full play to system performance and improve program execution efficiency. It should be clear that no matter how programmers write scheduling, they can only influence the thread execution order to the maximum extent, but cannot implement precise control. The thread sleep is one of the simplest ways to make the thread out of the CPU. When the thread sleep, the CPU resources are handed over to other threads so that the thread can be rotated for execution. When the thread sleep for a certain period of time, the thread will wake up and enter the preparation status to wait for execution. The Thread sleep methods are Thread. sleep (long millis) and Thread. sleep (long millis, int nanos). They are static methods. Which Thread does the sleep call? Simply put, the thread that calls sleep will sleep. /*** Java thread: Thread Scheduling-sleep ** @ author leizhimin 9:02:40 */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 + "times! "); Try {Thread. sleep (50);} 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 + "times! "); Try {Thread. sleep (50);} catch (InterruptedException e) {e. printStackTrace () ;}}} Thread 2 0th executions! Thread 1 executes 0th times! Thread 1 executes 1st times! Thread 2, 1st executions! Thread 1 executes 2nd times! Thread 2, 2nd executions! Process finished with exit code 0 can be seen from the output above that the thread execution order cannot be accurately guaranteed.

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.