java线程等待数_Java线程等待用法实例分析

本文实例讲述了Java线程等待用法。分享给大家供大家参考,具体如下:

线程等待

public class Hello {

public static void main(String[] args) {

A a = new A();

new Thread(new MyRun(a)).start();

new Thread(new MyRun1(a)).start();

}

}

class MyRun implements Runnable {

private A a;

public MyRun(A a) {

this.a = a;

}

@Override

public void run() {

synchronized (a) {

a.setTitle("hello");

try {

a.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

a.setNumber(12);

System.out.println(a);

}

}

}

class MyRun1 implements Runnable {

private A a;

public MyRun1(A a) {

this.a = a;

}

@Override

public void run() {

synchronized (a) {

a.setTitle("world");

a.setNumber(24);

a.notifyAll();

System.out.println(a);

}

}

}

class A {

private String title;

private Integer number;

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public Integer getNumber() {

return number;

}

public void setNumber(Integer number) {

this.number = number;

}

@Override

public String toString() {

return "A{" +

"title='" + title + '\'' +

", number=" + number +

'}';

}

}

运行输出:

A{title='world', number=24}

A{title='world', number=12}

线程等待,obj.wait(),会释放当前的锁,对象的普通方法,obj.wait(超时时间),表示指定时间后可以自动唤醒

线程唤醒,obj.notify(),唤醒一个线程,obj.notifyAll(),唤醒所以线程,obj需要和线程等待的对象一致。

wait和sleep的区别

个人认为:sleep就是一种延缓代码执行的方法,wait是有关多线程的一些高级操作。

希望本文所述对大家java程序设计有所帮助。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值