【Java k中Thread sleep和wait的区别】

今天我们来谈谈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) {

  //Thread.sleep(2000);

posted @ 2013-09-08 14:28  豆豆逗逗  阅读(204)  评论(0编辑  收藏  举报