Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1687309
  • 博文数量: 782
  • 博客积分: 2455
  • 博客等级: 大尉
  • 技术积分: 4140
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-06 21:37
个人简介

Linux ,c/c++, web,前端,php,js

文章分类

全部博文(782)

文章存档

2015年(8)

2014年(28)

2013年(110)

2012年(307)

2011年(329)

分类:

2011-12-03 10:11:56

原文地址:经典的多线程的题目 作者:xueliangfei

 

  1. class Info{
  2.  private String name = "AAA";
  3.  private String content = "BBB" ;
  4.  private boolean flag = false ;
  5.  public synchronized void set(String name,String content){
  6.   if(!flag){
  7.    try{
  8.     super.wait() ;
  9.    }catch(InterruptedException e){
  10.     e.printStackTrace() ;
  11.    }
  12.   }
  13.   this.setName(name) ;
  14.   try{
  15.    Thread.sleep(100) ;
  16.   }catch(InterruptedException e){
  17.    e.printStackTrace() ;
  18.   }
  19.   this.setContent(content) ;
  20.   flag = false ;
  21.   super.notify() ;
  22.  }
  23.  public synchronized void get(){
  24.   if(flag){
  25.    try{
  26.     super.wait() ;
  27.    }catch(InterruptedException e){
  28.     e.printStackTrace() ;
  29.    }
  30.   }
  31.   try{
  32.    Thread.sleep(300) ;
  33.   }catch(InterruptedException e){
  34.    e.printStackTrace() ;
  35.   }
  36.   System.out.println(this.getName() +
  37.    " --> " + this.getContent()) ;
  38.   flag = true ;
  39.   super.notify() ;
  40.  }
  41.  public void setName(String name){
  42.   this.name = name ;
  43.  }
  44.  public void setContent(String content){
  45.   this.content = content ;
  46.  }
  47.  public String getName(){
  48.   return this.name ;
  49.  }
  50.  public String getContent(){
  51.   return this.content ;
  52.  }
  53. };
  54. class Producer implements Runnable{
  55.  private Info info = null ;
  56.  public Producer(Info info){
  57.   this.info = info ;
  58.  }
  59.  public void run(){
  60.   boolean flag = false ;
  61.   for(int i=0;i<50;i++){
  62.    if(flag){
  63.     this.info.set("A","A") ;
  64.     flag = false ;
  65.    }else{
  66.     this.info.set("B","B") ;
  67.     flag = true ;
  68.    }
  69.   }
  70.  }
  71. };
  72. class Consumer implements Runnable{
  73.  private Info info = null ;
  74.  public Consumer(Info info){
  75.   this.info = info ;
  76.  }
  77.  public void run(){
  78.   for(int i=0;i<50;i++){
  79.    this.info.get() ;
  80.   }
  81.  }
  82. };
  83. public class ThreadDe{
  84.  public static void main(String args[]){
  85.   Info info = new Info();
  86.   Producer pro = new Producer(info) ;
  87.   Consumer con = new Consumer(info) ;
  88.   new Thread(pro).start() ;
  89.      new Thread(con).start() ;
  90.  }
  91. };
阅读(218) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~