服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

线程基础---wait(),notify的应用一例

 


本例子实现了两个线程,每个线程输出1到100的数字。第一个线程输出1-10,停止,通知第二个线程 输出1-10 第二个线程停止 通知第一个线程 输出11-20 ...实现的要点是在java中,每个对象都有个对象锁标志(object lock flag)与之想关联,当一个线程a调用对象的一段synchronized代码时,它首先要获取与这个对象关联的对象锁标志,然后执行相应的代码,执行结束后,把这个对象锁标志返回给对象;因此,在线程a执行synchronized代码期间,如果另一个线程b也要执行同一对象的一段synchronized代码时(不一定与线程a执行的相同),它将要等到线程a执行完后,才能继续....

如何利用wait() notify() notifyall()?

在synchronized代码被执行期间,线程可以调用对象的wait()方法,释放对象锁标志,进入等待状态,并且可以调用notify()或者notifyall()方法通知正在等待的其他线程。notify()通知等待队列中的第一个线程,notifyall()通知的是等待队列中的所有线程。

 
package jdeveloper.study;
/**
 * title:        jdeveloper's java projdect
 * description:  n/a
 * copyright:    copyright (c) 2001
 * company:      soho  http://www.chinajavaworld.com
 * @author jdeveloper@21cn.com
 * @version 1.0
 */
import java.lang.runnable;
import java.lang.thread;
public class demothread implements runnable{
  public demothread() {
         testthread testthread1 = new testthread(this,"1");
         testthread testthread2 = new testthread(this,"2");
         testthread2.start();
         testthread1.start();
  }
  public static void main(string[] args) {
    demothread demothread1 = new demothread();
  }
   public void run(){
        testthread t = (testthread) thread.currentthread();
        try{
          if (!t.getname().equalsignorecase("1")) {
              synchronized(this) {
                  wait();
              }
          }
          while(true){
            system.out.println("@time in thread"+ t.getname()+ "="+ t.increasetime());
            if(t.gettime()%10 == 0) {
              synchronized(this) {
                system.out.println("****************************************");
                notify();
                if ( t.gettime()==100 ) break;
                wait();
            }
          }
        }
        }catch(exception e){e.printstacktrace();}
    }
}
class testthread extends thread{
    private int time = 0 ;
    public testthread(runnable r,string name){
      super(r,name);
    }
    public int gettime(){
       return time;
    }
    public int increasetime (){
       return ++time;
    }
}


扫描关注微信公众号