当前位置: 移动技术网 > IT编程>开发语言>Java > 线程--继承Thread

线程--继承Thread

2018年03月02日  | 移动技术网IT编程  | 我要评论

首先继承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);
         }
    }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网