Thread sleep sleep

First, the role of sleep

sleep () defined in Thread.java.
the role of sleep () is to allow the current thread to sleep , that is, the current thread will enter from "running state" to "sleep (blocked) state." sleep () specifies the sleep time, sleep time thread may be greater than / equal to the sleep time; re-thread wakes up, it will be a "blocked" to "ready", so that the cpu waiting to be scheduled execution.

Comparing, sleep () and wait () of

Role wait () is to allow the current thread "running state" into the "wait (blocking) state", it would also release the synchronization lock. The role of sleep () is also let by the current thread "running state" into "sleep (blocked) state."
However, the wait () will release the synchronization lock objects , and sleep () will not release the lock .

// SleepLockTest.java的源码
public class SleepLockTest{ 

    private static Object obj = new Object();

    public static void main(String[] args){ 
        ThreadA t1 = new ThreadA("t1"); 
        ThreadA t2 = new ThreadA("t2"); 
        t1.start(); 
        t2.start();
    } 

    static class ThreadA extends Thread{
        public ThreadA(String name){ 
            super(name); 
        } 
        public  void RUN () { 
             // Get the object obj synchronization lock 
            the synchronized (obj) {
                 the try {
                     for ( int I = 0; I <10; I ++ ) { 
                        System.out.printf ( "% S:% D \ n-" , the this .getName (), I); 
                         // I can be divisible by four, the sleep 100 ms 
                        IF (I% 4 == 0 ) 
                            the Thread.sleep ( one hundred ); 
                    } 
                } the catch (InterruptedException E) { 
                    e.printStackTrace ( );  
                }
            }
        } 
    } 
}
View Code

Main thread start, two main threads t1 and t2. t1 and t2 in the run () reference the same object synchronization lock, i.e. synchronized (obj). T1 during operation, although it calls Thread.sleep (100); however, t2 is not going to get cpu execution rights. Because, t1 does not release "obj held Genlock"!
Note that, the program is executed again if we commented synchronized (obj), t1 and t2 can be switched with each other,

Guess you like

Origin www.cnblogs.com/myitnews/p/11422676.html