首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

Java Thread sleep跟wait的区别

2013-03-13 
Java Thread sleep和wait的区别我们在编写Java线程程序的时候,经常忽略sleep 和 wait方法的区别,导致一些

Java Thread sleep和wait的区别

我们在编写Java线程程序的时候,经常忽略sleep 和 wait方法的区别,导致一些非常棘手的问题,因此了解这两种方法区别有助于我们编写出更加优质的程序。

区别: 

                                            sleep()                                       wait() sleep为Thread类的方法 wait为object类的方法 sleep()睡眠时,保持对象锁 wait()睡眠时,释放对象锁 不能访问同步代码块 能够访问同步代码块

代码:

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);}}@Overridepublic 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();}}



热点排行