sleep和wait的区别

懒懒的小胖子 懒懒的小胖子
2018-11-21 09:13
90
0

wait方法需要在synchronized块里使用,阻塞当前线程,并且释放所持有对象的锁;sleep方法阻塞当前线程但是并不会释放锁,具体示例可以参考:http://www.whereta.com/article/detail/65

下面可以参考实例:

测试方法:

package com.vincent;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Vincent 创建于 2016/5/11.
 */
public class Main {
    public static void main(String[] args) {

        StringUtils.isBlank("");

        ExecutorService threadPool = Executors.newCachedThreadPool();
        final WaitDemo synchronizedDemo=new WaitDemo();

        for (int i=0;i<3;i++){
            threadPool.execute(new Runnable() {
                public void run() {
                    synchronizedDemo.a();
                }
            });

        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i=0;i<5;i++){
            threadPool.execute(new Runnable() {
                public void run() {
                    synchronizedDemo.b();
                }
            });
        }
    }
}

wait例子:

package com.vincent;

/**
 * Vincent 创建于 2016/5/12.
 */
public class WaitDemo {

    public synchronized void a() {
        while (true) {
            System.out.println("----a---" + System.currentTimeMillis());
            try {
                this.wait(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void b() {
        while (true) {
            System.out.println("----b---" + System.currentTimeMillis());
        }
    }


}

输出:

----a---1463054978359
----a---1463054978359
----a---1463054978359
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360
----b---1463054979360

从上面可以看出,先执行a方法,遇到a的wait释放锁,其他线程得以执行b方法

发表评论