• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: 小 中 大 | 推荐给好友 上一篇 | 下一篇

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

发布: 2007-7-04 13:34 | 作者: admin | 来源:  网友评论 | 查看: 11次 | 进入软件测试论坛讨论

领测软件测试网 本例子实现了两个线程,每个线程输出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 com.chinajavalab.study.thread;

/**
* Title:        Jasons's Java Projdect
* Copyright:    Copyright (c) ChinaJavaLab
* Company:      http://www.ChinaJavaLab.com
* @author       jason [email protected]
* @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;
    }


}

下载源程序       
  运行方法 (for windows):
  javac -d . DemoThread.java
  java -classpath .;%classpath% com.chinajavalab.study.thread.DemoThread
 

延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备2023014753号-2
技术支持和业务联系:[email protected] 电话:010-51297073

软件测试 | 领测国际 | ISTQB | ISTQB官网 | TMMi | TMMi认证 | 国际软件测试工程师认证 | 领测软件测试网