我们在编写Java线程程序的时候,经常忽略sleep 和 wait方法的区别,导致一些非常棘手的问题,因此了解这两种方法区别有助于我们编写出更加优质的程序。
区别:
| sleep() | wait() |
| sleep为Thread类的方法,用来控制线程自身流程 | wait为object类的方法,主要用于线程间通信 |
| sleep()睡眠时,保持对象锁 | wait()睡眠时,释放对象锁,使当前拥有该对象锁的线程等待,直到其他线程调用notify唤醒(备注:也可以使用超时唤醒) |
| 不能访问同步代码块 | 能够访问同步代码块 |
代码:
package com.jony.test;
public class ThreadTest implements Runnable {
int number = 10;
public void firstMethod() throws Exception {
System.out.println("first");
System.out.println(Thread.currentThread());
System.out.println(this);
synchronized (this) {
number += 100;
System.out.println(number);
notify();
}
}
public void secondMethod() throws Exception {
System.out.println("second");
System.out.println(Thread.currentThread());
System.out.println(this);
synchronized (this) {
/*
* sleep()睡眠时,保持对象锁,仍然占有该锁; 而wait()睡眠时,释放对象锁。 因此:
* (1)sleep不会访问其他同步代码块
* (2)wait 则会访问其他同步代码块
* (休息2S,阻塞线程)
* 以验证当前线程对象的锁被占用时, 是否可以访问其他同步代码块
*/
//Thread.sleep(2000);
//this.wait(2000);//只能在同步代码块中调用wait方法
this.wait();
System.out.println("Before: " + number);
number *= 200;
System.out.println("After: " + number);
}
}
@Override
public void run() {
try {
firstMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
ThreadTest threadTest = new ThreadTest();
Thread thread = new Thread(threadTest);
System.out.println(Thread.currentThread());
//thread.run(); // 不会创建新线程,直接调用run方法
thread.start();// 开始执行该线程(创建一个新线程),由Java虚拟机调用该线程的run方法
//Thread.sleep(1000);
threadTest.secondMethod();
}
}
1561

被折叠的 条评论
为什么被折叠?



