Java Thread sleep和wait的区别

我们在编写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();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值