search
HomeJavajavaTutorialWhat is the difference between java wait and sleep

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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft