【Java k中Thread sleep和wait的区别】
我们在编写Java线程程序的时候,经常忽略sleep 和 wait方法的区别,导致一些非常棘手的问题,因此了解这两种方法区别有助于我们编写出更加优质的程序。
区别:
sleep() wait()
sleep为Thread类的方法 wait为object类的方法
sleep()睡眠时,保持对象锁 wait()睡眠时,释放对象锁
不能访问同步代码块 能够访问同步代码块
代码:
[java]
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,阻塞线程)
更多精彩教程请关注:win2003系统下载