12.2.1继承Thread类创建多线程+多线程案例下面通过继承Thread类的方式来实现多线程。具体代码如下所示。publicclassExample02fpublicstaticvoidmain(Stringllargs)(MyThread02myThread=newMyThread020:Il创建MyThread02的线程对象myThread.startO,//开启线程while(true)(//通过死循环语句打印输出System.out.println(main(方法在运行");11classMyThreado2extendsThread(publicvoid runofwhile(true)(//通过死循环语句打印输出System.out.println("MyThread类的runO方法在运行");1
12.2.1 继承Thread类创建多线程 多线程案例 public class Example02 { public static void main(String[] args) { MyThread02 myThread = new MyThread02(); // 创建MyThread02的线程对象 myThread.start(); // 开启线程 while (true) { // 通过死循环语句打印输出 System.out.println("main()方法在运行"); } } } class MyThread02 extends Thread { public void run() { while (true) { // 通过死循环语句打印输出 System.out.println("MyThread类的run()方法在运行"); } } } 下面通过继承Thread类的方式来实现多线程。具体代码如下所示
12.2.1继承Thread类创建多线程运行结果运行代码,控制台显示的运行结果如下图所示。oRun:Example02XHyThread类的run(方法在运行NyThread类的runO方法在运行3NyThread类的run(方法在运行NyThread类的run方法在运行o司NyThread类的run方法在运行养ain(方法在运行RainO方法在运行团main(方法在运行nainO方法在运行由图可知,两个循环中的语句都有输出,说明程序实现了多线程
12.2.1 继承Thread类创建多线程 运行结果 运行代码,控制台显示的运行结果如下图所示。 由图可知,两个循环中的语句都有输出,说明程序实现了多线程
12.2.1继承Thread类创建多线程单线程和多线程的区别表示已执行战正在热行表示未热行从图可以看出,单线程的程序在运行单线程多线程时,会按照代码的调用顺序执行,而main()main()在多线程中,mainO方法和MyThreadMyThread.run()myThread.start()类的run0方法却可以同时运行,互不MyThread.runD影响。main(JwhileMyThread.run()whileMyThread.runO.whilemain()while
12.2.1 继承Thread类创建多线程 单线程和多线程的区别 从图可以看出,单线程的程序在运行 时,会按照代码的调用顺序执行,而 在多线程中,main()方法和MyThread 类的run()方法却可以同时运行,互不 影响
12.2.2室实现Runnable接口创建多线程先定一个小目标!掌握实现Runnable接口创建多线程,能够通过实现Runnable接口的方式创建多线程
12.2.2 实现Runnable接口创建多线程 先定一个小 目标! 掌握实现Runnable接口创建多线程,能够 通过实现Runnable接口的方式创建多线程
12.2.2实现Runnable接口创建多线程继承Thread类实现多线程的擎端通过继承Thread类实现了多线程,但是这种方式有一定的局限性。因为Java只支持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类Studen继承了Person类,那么Student类就无法再通过继承Thread类创建线程
12.2.2 实现Runnable接口创建多线程 通过继承Thread类实现了多线程,但是这种方式有一定的局限性。因为Java只支 持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类 Student继承了Person类,那么Student类就无法再通过继承Thread类创建线程。 继承Thread类实现多线程的弊端