服务热线:13616026886

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

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

[java100例]064、线程间通讯


  /**
 * <p>title: 线程间合作</p>
 * <p>description: 本实例使用二个线程共同合作绘制一个实体三角。</p>
 * <p>copyright: copyright (c) 2003</p>
 * <p>filename: mainthread.java</p>
 * @version 1.0
 */
public class mainthread{
  public static int flag = 0;
  int count = 10;
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(string[] arg){
    new mainthread();
  }
/**
 *<br>方法说明:构造器,启动两个子线程。
 *<br>输入参数:
 *<br>返回类型:
 */
  mainthread(){
    thread1 t1 = new mainthread.thread1(this.count);
    thread2 t2 = new mainthread.thread2(this.count);
    //启动两线程
    t1.start();
    t2.start();
    //让线程一首先工作。
    flag = 1;
  }
/**
 *<br>类说明:内部类,继承了thread,
 *<br>类描述:实现了在输出每行前面的空格。
 */
  class thread1 extends thread{
    int count1 = 0;
    thread1(int i){
      count1 = i;
    }
    public void run(){
     
      while(true){
       if(count1<=0) break;
       if(mainthread.flag==1){
        
         for(int i=0;i<count1;i++){
           system.out.print(" ");
         }
         count1--;
         mainthread.flag=2;
        }
      }
    }
  }
/**
 *<br>类说明:内部类,继承了thread,
 *<br>类描述:实现了在输出每行第“*”号。并提供换行。
 */
  class thread2 extends thread{
    int count2 = 0;
    thread2(int i){
      count2 = i;
    }
    public void run(){
      int count = 0;
      while(true){
        if(count>=count2) break;
        if(mainthread.flag==2){
         for(int i=0;i<(count*2+1);i++){
           system.out.print("*");
         }
         system.out.print("");
         count++;
         mainthread.flag=1;
        }
      }
    }
  }
}

扫描关注微信公众号