码迷,mamicode.com
首页 > 编程语言 > 详细

java线层的启动与停止

时间:2015-08-09 20:36:09      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

class Do8
{
    public static void main(String[] args) 
    {
           Resource r =new Resource();
           
           Input in =new Input(r);
           Output out=new Output(r);
            Thread t1=new Thread(in);
            Thread t2=new Thread(out);
            t1.start();
            t2.start();
    }
}

class Resource
{
    String name;
    String sex;
    boolean flag=false;
}
//输入
class Input implements Runnable
{
    Resource r;
    Input(Resource r)
    {
    this.r=r;
    }
    public void run()
    {
    int x=0;
    while(true)
        {
        synchronized(r)
            {
           if(r.flag)
                {
            try{r.wait();}catch(Exception e){}//为真的时候,当前线层停止
                }
               if(x==0)
                    {
                    r.name="往里";
                    r.sex="男";
                     }
                     else
                    {
                      r.name="xiaoli";
                      r.sex="wumen";
                     }
                     r.flag=true;
                r.notify();//启动任意的停止的线层
                 
              }
                
            x=(x+1)%2;    
            
        }
    }
}
//输出
class Output implements Runnable
{
    Resource r;
    Output(Resource r)
    {
    this.r=r;
    }
    public void run()
    {
        while(true)
        {
            synchronized(r)
                {
                if(!r.flag)
                    {
                    try{r.wait();}catch(Exception e){}//不为真的时候,当前线层停止
                    }
                    try{Thread.sleep(100);}catch(Exception e){}
                    System.out.println(r.name+"..."+r.sex);
                    r.flag=false;
                    r.notify();//启动任意的停止的线层
                    
                }
        }
    }
}

 

java线层的启动与停止

标签:

原文地址:http://www.cnblogs.com/zywf/p/4716201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!