run( ) 与 start( )

来源:互联网 发布:姚明cba数据 编辑:程序博客网 时间:2024/05/16 11:21
看一下下面的代码:
 
class Father implements Runnable
{
       private String name;
       private int times;
 
      Father(String name,int times)
     {
         this.name  = name;
         this.times = times;
     }
 
     public void run()
     {
         try
         {
            for(int i = 0;i<this.times;i++)
            {
               Thread.sleep(1000);
              System.out.println(i+ "I'm father.my name"+this.name);
            }
         }
         catch(Exception e)
        {
             System.out.println(e.toString());
        }
   
    }
}

class Child implements Runnable
{
       private String name;
       private int times;
  
       Child(String name,int times)
       {
            this.name  = name;
            this.times = times;
       }
  
       public void run()
      {
           try
           {
               for(int i = 0;i<this.times;i++)
               {
                   Thread.sleep(1000);
                   System.out.println(i+
                      "I'm child.My name is "+this.name);
               }
           }
           catch(Exception e)
          {
               System.out.println(e.toString());
          }
  
     }
}

public class Filiation
{
      public static void main(String [] args)
      { 
           /*
           Thread t1 = new Thread(new Father("ffff",10));
           Thread t2 = new Thread(new Child("ccccc",10));
           t1.start();//创建一个新的线程,并运行 Father 的run()
           t2.start();//创建一个新的线程,并运行 Child 的run()
           */
    
    
           Father f = new Father("father",5);
           Child  c = new Child("child",5);
           f.run(); //并没有创建一个新的进程
           c.run(); //并没有创建一个新的进程
      }
}
 
 
代码很简单:有三个类。Father、Child 实现了Runnable接口,类Fatcher和类Child中的run() 方法是先 睡眠 1秒,然后输出显示相关信息。其它输出结果是:
 
I'm father .my name is father
1 I'm father .my name is father
2 I'm father .my name is father
3 I'm father .my name is father
4 I'm father .my name is father
0 I'm child . My name is child
1 I'm child . My name is child
2 I'm child . My name is child
3 I'm child . My name is child
4 I'm child . My name is child
 
而将main()中有内容变为:

    Thread t1 = new Thread(new Father("ffff",10));
    Thread t2 = new Thread(new Child("ccccc",10));
    t1.start();//创建一个新的线程,并运行 Father 的run()
    t2.start();//创建一个新的线程,并运行 Child 的run()
        
    /*
    Father f = new Father("father",5);
    Child  c = new Child("child",5);
    f.run();
    c.run();
    */
 
编译后,执行得如下结果:
 
I'm father .my name is father
0 I'm child . My name is child
1 I'm father .my name is father
1 I'm child . My name is child
2 I'm father .my name is father
2 I'm child . My name is child
3 I'm father .my name is father
3 I'm child . My name is child
4 I'm father .my name is father 
 
 
所以在要创建线程时:用start()方法启动一个线程。不要用run(),因为run()是Runnable的接口方法而已,除此之外跟一般的方法没什么不同(在当前线程中运行)。而start()则不一样,它会启动一个新的线程,然后让run()方法在新的线程上执行。