线程创建的第二种方法

第一种方法是继承并且重写run方法(不推荐使用)

第二种就是有爹的情况,用实现接口的形式拓展功能——实现Runnable接口

Runnable中只有run()方法

今天复习同步线程代码时候卡在一个问题上:

class SynThread implements Runnable
{
  run()
  {
    
  }
}

class Main
{
  public static void main(string [] args)
  {
    SynThread syn=new SynThread();
    Thread a=new Thread(syn);                      //问题:为啥要传syn进去???  问答 因为不传syn,Thread类里的
    a.start();                       //Runnable引用就没有值  
  }
}

  

 

 后来看了毕老师视频后才明白。

    解释:

//Thread有一种Thread(Runnable a) 的初始化方法
class Thread implements Runnable
{
  private Runnable i;
  Thread(Runnable i)   //
  {
    this i=i;
  }

  run()//Thread类实现的Runnable方法    //
  {
    i.run();
  }

  strat()
  {
    run();     //
  }
}

class SynThread implements Runnable
{
  run()     //
  {
    syso("子类SubThread");
   }
}

class SubThread extend Thread
{
  run()   //
  {
    syso("子类SubThread");
  }
}


class Main
{
  public static void main(...)
  {
    SubTread sub=new SubThread();
    sub.start(); //      由-->

    Thread th=new Thread();
    th.strat();   // 有①-->②   但是这时i无值,所以会报错,可以在②里加上判断语句

     
    SynThread syn=new SynThread();
    Thread th=new Thread(syn);   //这里直接进入④ 给i赋了值
    th.start();  //  ①-->②-->⑤

  } 
}

  

  

 

猜你喜欢

转载自www.cnblogs.com/zzw3014/p/9751900.html