线程--继承Thread

首先继承Thread类,然后重写Thread类的run()方法。

Thread类的子类的对象调用start()方法,然后虚拟机就会调用该线程的run()方法。

当程序执行到start()方法时,线程启动,此时有两条执行路径,一条是主方法执行main方法,另一条是线程路径执行线程run()里的代码,两条路径交替执行(交替执行指抢夺cup执行时间,所以每次执行结果都不同)

class ThreadDemo extends Thread
{
    public void run()//存储线程要执行的代码
    {  
         for(int i = 0; i < 60; i++)
         {
               System.out.println("线程 " + i);
         }
    }   
}



class ThreadTest
{
    public static void main(String[] args)
    {
          ThreadDemo thread = new ThreadDemo();
          thread.start();//线程启动,并执行该线程的run()方法,main路径和线程交替执行
         
          for(int i = 0; i < 60; i++)
         {
               System.out.println("mian " + i);
         }
    }
}
posted @ 2018-03-01 22:11  弓长张&木子李  阅读(282)  评论(0编辑  收藏  举报