sleep 与 wait

比较:

相同点:都可以使线程暂停执行

不同点:sleep不会释放锁,wait会释放锁,让出资源

package com.nd.app.test;

/**
 * @author JiaJiCheng
 * @date 2017年8月25日 下午2:06:31
 * 
 */
public class SleepThread implements Runnable {
	volatile int number = 10;

	public void firstMethod() throws Exception {
		synchronized (this) {
			System.out.println("first thread-" + Thread.currentThread().getName());

			/**
			 * sleep 不会释放锁,依然持有锁 wait 会释放锁,让出资源
			 */
			Thread.sleep(3000);
//			 this.wait(3000);
			number += 100;
			System.out.println("first:" + number);
		}
	}

	public void secondMethod() throws Exception {
		synchronized (this) {
			System.out.println("second thread-" + Thread.currentThread().getName());

			number *= 200;
			System.out.println("second:" + number);
		}
	}

	public void run() {
		try {
			firstMethod();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SleepThread threadTest = new SleepThread();
		Thread thread = new Thread(threadTest);
		thread.start();
		try {
			// 确保先执行子线程中的代码
			Thread.sleep(500);

			threadTest.secondMethod();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
以上代码解释如下:

使得子线程先执行,在子线程中讨论sleep与wait。新建了一个SleepThread对象,创建子线程开始执行,Thread.sleep(3000),使子线程暂停3秒钟再执行,主线程开始执行secondMethod()方法,虽然子线程休眠了但是main线程还是不能访问对象,这是因为此时子线程使用的Sleep方法不释放对象锁,导致其他线程无法访问SleepThread对象,wait反之。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值