日历

2008 8.22 Fri
     12
3456789
10111213141516
17181920212223
24252627282930
31      
«» 2008 - 8 «»

文章搜索

日志文章

2007年09月10日 16:53:27

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;


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;
  }


}

Tags: java   notify   wait  

类别: J2SE |  评论(2) |  浏览(9926) |  收藏
2楼 [匿名]空中楼阁 2008年05月08日 08:43:40 Says:
我终于有点明白了
1楼 [匿名]www.abcnic.com 2007年12月18日 18:55:29 Says:

全国第一家虚拟主机:支持伪静态.有利于提高排名

15G全能空间年付500元/月付70元 可免费试用
5GB 独立WEB空间、5GB 企业邮箱空间、5GB MSSQL数据库
(可划分5个数据库。可独立放5个不同的站点)

IIS连接数据 500 个、500GB/月流量、共享日志文件空间

企业邮箱功能
赠送5GB 超大企业邮箱,500个Email企业邮箱用户
自动回复、自动转发、POP3、SMTP收发信、SMTP发信认证
邮件过滤、邮件拒收、邮件夹管理、邮件域管理、定制邮件数

数据库功能
支持5GB MSSQL数据库空间,5个用户数据库、Access

主机功能支持
采用安全稳定的Win2003 .net2.0 架构
支持ASP、PHP、ASP.NET、PERL等脚本、支持自定义CGI
全面支持.net2.0版本,独立的Application应用池,
支持SSI(Shtml),支持FrontPage扩展
可免费自行绑定5个域名、500个解析、500个子域名

详情咨询QQ:443933
发表评论