比较:
相同点:都可以使线程暂停执行
不同点:sleep不会释放锁,wait会释放锁,让出资源
package com.nd.app.test;
/**
* @author JiaJiCheng
* @date 2017年8月25日 下午2:06:31
*
*/
public class SleepThread implements Runnable {
volatile int number = 10;
public void firstMethod() throws Exception {
synchronized (this) {
System.out.println("first thread-" + Thread.currentThread().getName());
/**
* sleep 不会释放锁,依然持有锁 wait 会释放锁,让出资源
*/
Thread.sleep(3000);
// this.wait(3000);
number += 100;
System.out.println("first:" + number);
}
}
public void secondMethod() throws Exception {
synchronized (this) {
System.out.println("second thread-" + Thread.currentThread().getName());
number *= 200;
System.out.println("second:" + number);
}
}
public void run() {
try {
firstMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SleepThread threadTest = new SleepThread();
Thread thread = new Thread(threadTest);
thread.start();
try {
// 确保先执行子线程中的代码
Thread.sleep(500);
threadTest.secondMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码解释如下:
使得子线程先执行,在子线程中讨论sleep与wait。新建了一个SleepThread对象,创建子线程开始执行,Thread.sleep(3000),使子线程暂停3秒钟再执行,主线程开始执行secondMethod()方法,虽然子线程休眠了但是main线程还是不能访问对象,这是因为此时子线程使用的Sleep方法不释放对象锁,导致其他线程无法访问SleepThread对象,wait反之。