sleep() and wait() in java are the same and different in detail

Keywords: Java

sleep() and wait() in java are the same and different in detail

identical

Thread_ sleep and Object_ wait methods in java both suspend the current thread, which gives up CPU usage. There is no need to call sleep to occupy the CPU, and call wait does not occupy the CPU. If you see a similar statement, please automatically filter.

difference

1. The sleep method is a static method of the Thread class, while wait is a method of Object.

2. It is impossible to wake up manually after invoking sleep. The sleeping timeout thread will wake up automatically when invoking sleep. After invoking wait, the notify (notify is also an Object method) can be used to wake up the thread. At the same time, wait also has a parameter method. After waiting passes in the sleep time, the sleeping timeout thread will be waked up automatically.

3. If synchronous locks are used in threads. Synchronization locks will not be released until sleep is invoked; wait must be invoked in the block of synchronization code, and synchronization locks will be released after wait is invoked.

interpretative statement

1. What is the synchronization lock and what is the synchronization code block?

What is synchronization lock? Imagine linking multiple computers to a printer. If three calls are printed at the same time, who should they print to first, or print to multiple computers at the same time? Printer is a limited resource, and its working principle also determines that he can not accomplish multi-tasking at the same time, so the printer must be printed in sequence. If someone requests printing in the process of using the printer, then the request can not be executed immediately, and the request can not be continued until the last printing task is completed. At this time, the concept of synchronous lock was born. I locked it when I was using the printer. When someone visited the printer, he found that the printer was locked and could only wait. When I finished using the printer, the printer lock was opened. When someone visited the printer and found that the printer had no lock, he could use the printer. Our common part is a lock. When we want to use shared resources, we first check whether the lock has a lock. We call this lock synchronous lock.

There is no concept of PV in java, but there is a way to deal with multithreading. Java provides us with synchronized keywords. When we need to deal with concurrency problems, we can use synchronized keywords to lock objects or classes. It should be noted that the synchronization lock is released only after the execution of the code in the synchronization block is completed.

// Locking Object 1
Object obj = new Object();
synchronized (obj) {
    try {
        obj.wait();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

// Locking Objects 2
// This pointer represents an object of the current class, so locking this is equivalent to locking a single object. The single object access of this class is mutually exclusive, but each object does not affect each other.
synchronized (this){
    this.wait();
}

// Locking Class 1
// For class locking, all object access of this class is mutually exclusive, and when one object is occupied, other objects are inaccessible.
// The synchronized parameter passes in the class name to indicate that the class is locked.
synchronized (Demo.class){
    Demo.class.wait();
}

// Locking Class 12
// Static attributes belong to classes rather than objects, so locking static attributes of classes is actually locking classes.
// Locking a static property of a class
synchronized (Demo.STATIC_VALUE){
}

2. chestnuts

/**
 * Created by lion on 2017/2/5.
 */
public class ThreadDemo {

    public Float value = 1.23f;

    public static void main(String[] args) {
        demo1();
        demo2();
    }

    /**
     * demo1 Verify that {@see Thread#sleep(long)} does not affect the role of synchronization locks after a thread hibernates.
     */
    private static void demo1() {
        final ThreadDemo threadDemo = new ThreadDemo();

        System.out.println(Thread.currentThread().getName() + " value = " +
                threadDemo.value);

        new Thread(() -> {
            synchronized (threadDemo) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " value = " +
                        threadDemo.value);
            }
        }).start();

        // Here, in order to ensure that the former thread executes first than the latter one, let the current thread sleep for a while.
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (threadDemo) {
                threadDemo.value = 2.34f;
                System.out.println(Thread.currentThread().getName() + " value = " +
                        threadDemo.value);
            }
        }).start();
    }

    /**
     * demo2 Verify that the {@see Object#wait()} call immediately releases the synchronization lock.
     * It also demonstrates how to wake up a thread that has been wait ed.
     */
    private static void demo2() {
        final ThreadDemo threadDemo = new ThreadDemo();

        System.out.println(Thread.currentThread().getName() + " value = " +
                threadDemo.value);

        new Thread(() -> {
            synchronized (threadDemo) {
                try {
                    threadDemo.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " value = " +
                        threadDemo.value);
            }
        }).start();

        // Here, in order to ensure that the former thread executes first than the latter one, let the current thread sleep for a while.
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (threadDemo) {
                System.out.println(Thread.currentThread().getName() + " value = " +
                        threadDemo.value);
                threadDemo.notify();
            }
        }).start();
    }
}

demo1 results:

main value = 1.23
Thread-0 value = 1.23
Thread-1 value = 2.34

From the results of demo 1, we can see that Thread-1 can not be executed until the completion of Thread-0 execution, which shows that sleep method can not release synchronization lock in synchronization block.

demo2 results:

main value = 1.23
Thread-1 value = 1.23
Thread-0 value = 1.23

From the results of demo2, we can see that the synchronization lock is released after calling wait, so the synchronization block in Thread-1 can be executed, and Thread-1 wakes up Thread-0 after execution.

Posted by cassius on Fri, 22 Mar 2019 04:45:53 -0700