java里等待,Java中线程的等待与唤醒的介绍(代码)

本篇文章给大家带来的内容是关于Java中线程的等待与唤醒的介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

class ThreadA extends Thread{

public ThreadA(String name) {

super(name);

}

public void run() {

synchronized (this) {

System.out.println(Thread.currentThread().getName()+" call notify()");

notify();

}

}

}

public class WaitTest {

public static void main(String[] args) {

ThreadA t1 = new ThreadA("t1");

synchronized(t1) {

try {

// 启动“线程t1”

System.out.println(Thread.currentThread().getName()+" start t1");

t1.start();

// 主线程等待t1通过notify()唤醒。

System.out.println(Thread.currentThread().getName()+" wait()");

t1.wait();

System.out.println(Thread.currentThread().getName()+" continue");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

输出结果:main start t1 -> main wait() -> t1 call notify() -> main continue

其实调用t1.start(),t1为就绪状态,只是main方法中,t1被main线程锁住了,t1.wait()的时候,让当前线程等待,其实是让main线程等待了,然后释放了t1锁,t1线程执行,打印t1 call notify(),然后唤醒main线程,最后结束;

这里说一下wait()与sleep()的区别,他们的共同点都是让线程休眠,但是wait()会释放对象同步锁,而sleep()不会;下面的代码t1结束之后才会运行t2;能够证实这一点;

public class SleepLockTest{

private static Object obj = new Object();

public static void main(String[] args){

ThreadA t1 = new ThreadA("t1");

ThreadA t2 = new ThreadA("t2");

t1.start();

t2.start();

}

static class ThreadA extends Thread{

public ThreadA(String name){

super(name);

}

public void run(){

synchronized (obj) {

try {

for(int i=0; i <10; i++){

System.out.printf("%s: %d\n", this.getName(), i);

// i能被4整除时,休眠100毫秒

if (i%4 == 0)

Thread.sleep(100);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值