当前位置:网站首页>The difference between the sleep () method and the wait () method of a thread

The difference between the sleep () method and the wait () method of a thread

2022-06-24 10:24:00 Ugly and ugly

in general , Thread sleep() Methods and wait() Methods have the following differences :

(1)sleep() The method is Thread Methods in class , and wait() The method is Object Methods in class .

(2)sleep() Method will not release lock, however wait() Method will release , And will join the waiting queue .

(3)sleep() Method does not depend on synchronizer synchronized(), however wait() Method Need to rely on synchronized keyword .

(4) Thread calls sleep() You don't need to wake up later ( Start blocking during sleep , The monitoring state of the thread remains , When the specified sleep time is up, it will automatically resume the running state ), however wait() Methods need to be reawakened ( Don't set a time and need to be interrupted by someone else ).

public class SleepDemo {

    public static final Object LOCK = new Object();

    public static void main(String[] args) {
        Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
            @Override
            public void run() {
                new SleepDemo().testSleep();
            }
        }.start());
    }

    private void testSleep() {
        synchronized (LOCK) {
            try {
                System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
                //  Sleep  2 s
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
            } catch (Exception e) {

            }
        }
    }

}

You can see , Threads 1 Got the resources first , Sleep is required when executing the main method 2 second , So in these two seconds , Even if the thread 1 There's no movement , Threads 2 Nor can it preempt resources . It should be noted that , Calling sleep() When the method is used , If there are two threads , To achieve the effect of thread sleep, you need to use synchronized() Method , Otherwise, the effect will not be achieved .

public class SleepDemo {

//    public static final Object LOCK = new Object();

    public static void main(String[] args) {
        Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
            @Override
            public void run() {
                new SleepDemo().testSleep();
            }
        }.start());
    }

    private void testSleep() {
//        synchronized (LOCK) {
            try {
                System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
                //  Sleep  2 s
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
            } catch (Exception e) {
                System.out.println(e);
            }
//        }
    }

}

As shown above , Don't use synchronized() Two threads will execute at the same time , Simultaneous sleep , At the same time, the execution is resumed .

Thus we can see that , call sleep() When the method is used , Is not strongly dependent on synchronized() Method , If I have only one thread , So use synchronized() Methods and do not use synchronized() The effect of the method is the same . If there are two threads , You can also choose to use or not use synchronized() Method . however wait() The approach is different ,wait() Methods are strongly dependent on synchronized() Method , If not used synchronized() Method words ,wait() Method will report an error .

public class WaitDemo {

    public static final Object LOCK = new Object();

    public static void main(String[] args) {
        Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
            @Override
            public void run() {
                WaitDemo.testWait();
            }
        }.start());
    }

    private static void testWait() {
//        synchronized (LOCK) {
            try {
                System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
                //  wait for  2 s
                LOCK.wait(2000);
                System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
//    }

}

Use synchronized After keyword modification :

public class WaitDemo {

    public static final Object LOCK = new Object();

    public static void main(String[] args) {
        Stream.of(" Threads 1", " Threads 2").forEach(a -> new Thread(a) {
            @Override
            public void run() {
                WaitDemo.testWait();
            }
        }.start());
    }

    private static void testWait() {
        synchronized (LOCK) {
            try {
                System.out.println(Thread.currentThread().getName() + " Being implemented : " + System.currentTimeMillis() / 1000);
                //  wait for  2 s
                LOCK.wait(2000);
                System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }

}

Because it is specified in the code wait(2000), So when 2 Seconds later, the thread will resume execution , Without another thread to wake up , If wait() Method does not specify a time , Then the thread will wait ~

besides , Once a thread is wait after , There must be another thread to wake up , Otherwise, it will be in a waiting state .

public class WaitDemo {

    public static final Object LOCK = new Object();

    private void testWait1() {
        synchronized (LOCK) {
            try {
                System.out.println(Thread.currentThread().getName() + " Start execution : " + System.currentTimeMillis() / 1000);
                LOCK.wait();
                System.out.println(Thread.currentThread().getName() + " Resume execution : " + System.currentTimeMillis() / 1000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    private void testNotify() {
        synchronized (LOCK) {
            try {
                Thread.sleep(2000);
                LOCK.notify();
                System.out.println(Thread.currentThread().getName() + " Wake up another thread : " + System.currentTimeMillis() / 1000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                new WaitDemo().testWait1();
            }
        }.start();
        new Thread() {
            @Override
            public void run() {
                new WaitDemo().testNotify();
            }
        }.start();
    }

}

 

  This article references from :sleep() and wait() Difference analysis of - Nuggets

原网站

版权声明
本文为[Ugly and ugly]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240916245098.html