当前位置: 移动技术网 > IT编程>开发语言>Java > Java线程等待用法实例分析

Java线程等待用法实例分析

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《java进程与线程操作技巧总结》、《java数据结构与算法教程》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》和《java缓存操作技巧汇总

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网