测试sleep对锁的影响

测试sleep对锁的影响

package ch1.base.safeend;


//测试sleep对锁的影响
/*
1.sleep()方法
在指定时间内让当前正在执行的线程暂停执行,但不会释放“锁标志”。不推荐使用。
sleep()使当前线程进入阻塞状态,在指定时间内不会执行。
 sleep()会让线程交出CPU的执行权,但是不会释放锁。


 */
public class SleepLock {
    private Object lock = new Object();


    private class ThreadSleep extends Thread{
        public void run(){
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName+" will take the lock");
            try{
              synchronized (lock) {
                  System.out.println(threadName+" taking the lock");
                  Thread.sleep(5000);
                  System.out.println("finish the work:"+threadName);
              }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }

    private class ThreadNoteSleep extends Thread{
        public void run(){
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName+" will take the lock time="+System.currentTimeMillis());
            synchronized (lock){
                System.out.println(threadName+" taking the lock time="+System.currentTimeMillis());
                System.out.println("Finish the work:"+ threadName);
            }
        }
    }

    public static void main(String[] args) {
        SleepLock sleepLock = new SleepLock();
        Thread threadA = sleepLock.new ThreadSleep();
        threadA.setName("ThreadSleep");

        Thread threadB = sleepLock.new ThreadNoteSleep();
        threadB.setName("ThreadNotSleep");
        threadA.start();
        try{
            Thread.sleep(1000);
            System.out.println(" main sleep!");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        threadB.start();
    }

    /*
    ThreadSleep will take the lock
    ThreadSleep taking the lock
     main sleep!
    ThreadNotSleep will take the lock time=1579358799866
    finish the work:ThreadSleep
    ThreadNotSleep taking the lock time=1579358803867
    Finish the work:ThreadNotSleep

    Process finished with exit code 0
         */
}

你可能感兴趣的:(测试sleep对锁的影响)