Home  >  Article  >  Java  >  What is the difference between java wait and sleep

What is the difference between java wait and sleep

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-27 15:15:303580browse

What is the difference between java wait and sleep

What is the difference between java wait and sleep

So the biggest difference between sleep() and wait() methods is:

·When sleep() sleeps, the object lock is maintained and the lock is still occupied;

·When wait() sleeps, the object lock is released.

·But both wait() and sleep() can interrupt the pause state of the thread through the interrupt() method, causing the thread to immediately throw InterruptedException (but This method is not recommended).

/**
 * Created by jiankunking on 2018/4/5.
 */
public class ThreadTest implements Runnable {
    int number = 10;
    public void addHundred() throws Exception {
        System.out.println("addHundred  begin");
        synchronized (this) {
            number += 100;
            System.out.println("addHundred:" + number);
        }
        System.out.println("addHundred  end");
    }
    public void wait2Seconds() throws Exception {
        System.out.println("wait2Seconds begin ");
        synchronized (this) {
            /**
             * (休息2S,阻塞线程)
             * 以验证当前线程对象的机锁被占用时,
             * 是否被可以访问其他同步代码块
             */
            System.out.println(".............wait begin..................");
            this.wait(2000);
            number *= 200;
            System.out.println(".............wait end..................");
        }
        System.out.println("wait2Seconds end ");
    }
    public void sleep2Seconds() throws Exception {
        System.out.println("sleep2Seconds begin ");
        synchronized (this) {
            /**
             * (休息2S,阻塞线程)
             * 以验证当前线程对象的机锁被占用时,
             * 是否被可以访问其他同步代码块
             */
            System.out.println("............sleep begin...................");
            Thread.sleep(2000);
            number *= 200;
            System.out.println(".............sleep end..................");
        }
        System.out.println("sleep2Seconds end ");
    }
    @Override
    public void run() {
        try {
            addHundred();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        ThreadTest threadTest = new ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        //threadTest.sleep2Seconds();
        //threadTest.wait2Seconds();
    }
}

When threadTest.sleep2Seconds(), the output result is as follows:

What is the difference between java wait and sleep

When threadTest.wait2Seconds(), the output result is as follows:

What is the difference between java wait and sleep

sleep2Seconds()/wait2Seconds() is represented by secondMethod():

Let’s briefly analyze this code. Instantiate ThreadTest in the main() method and start the thread, and then call a method (secondMethod()) of the thread. Because the method is called in the main thread, the called ordinary method secondMethod()) will be executed first (but it is not the thread method of the object that finishes executing the ordinary method. Execution, during the execution of ordinary methods, the methods of the thread will also be executed. They are executed alternately, except that the ordinary methods in the main thread will be executed first), so when the program is running, secondMethod() will be executed first, and secondMethod There is a synchronized block in the () method code fragment, so after the secondMethod method is executed, the method will occupy the object's machine lock, causing the object's thread method to be blocked and cannot be executed until secondeMethod releases the lock;

When using the Thread.sleep(2000) method, because sleep blocks the thread and holds the object lock, other synchronized threads (secondMethod()) of the object cannot be executed until the synchronized block is executed (sleep is completed) , the secondMethod() method can be executed, so the output result is:

number*200+100;

When using this.wait(2000) method, the secondMethod() method also locks the machine lock of the object after being executed, and executes to this .wait(2000), the method will sleep for 2S and release the currently held lock. At this time, the synchronization method of the thread will be executed (because the lock held by secondMethod has been released by wait()), so the output The result is:

number+100;

Several points to note about the sleep method in Java:

1. The Thread.sleep() method is used to pause the execution of the thread and put the CPU to the thread scheduler.

2. The Thread.sleep() method is a static method, which pauses the currently executing thread.

3. Java has two sleep methods, one has only one millisecond parameter, and the other has two parameters, milliseconds and nanoseconds.

4. Unlike the wait method, the sleep method does not release the lock.

5. If another thread interrupts a sleeping thread, the sleep method will throw Interrupted Exception.

6. A dormant thread is not guaranteed to get the CPU after waking up. It will enter the ready state first and compete with other threads for the CPU.

7. There is an error-prone place. When t.sleep() is called, thread t will be suspended. This is wrong because Thread.sleep is a static method that puts the current thread to sleep instead of thread t.

8. The wait method must be used in a synchronized environment, such as a synchronized method or a synchronized code block. If you do not use it under synchronized conditions, an IllegalMonitorStateException will be thrown. In addition, the sleep method does not need to be called under synchronous conditions, you can use it normally.

9. The wait method is used and defined in the Object class, while the sleep method operates on the current thread and is defined in the java.lang.Thread class.

PHP Chinese website has a large number of free JAVA introductory tutorials, everyone is welcome to learn!

The above is the detailed content of What is the difference between java wait and sleep. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn