zoukankan      html  css  js  c++  java
  • JAVA通过继承Thread来创建线程

    创建一个线程的第二种方法是创建一个新的类,该类继承Thread类,然后创建一个该类的实例。
    继承类必须重写run()方法,该方法是新线程的入口点。它也必须调用start()方法才能执行。

    实例

    // 通过继承 Thread 创建线程
    class NewThread extends Thread {
       NewThread() {
          // 创建第二个新线程
          super("Demo Thread");
          System.out.println("Child thread: " + this);
          start(); // 开始线程
       }
    
       // 第二个线程入口
       public void run() {
          try {
             for(int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                                // 让线程休眠一会
                Thread.sleep(50);
             }
          } catch (InterruptedException e) {
             System.out.println("Child interrupted.");
          }
          System.out.println("Exiting child thread.");
       }
    }
    
    public class ExtendThread {
       public static void main(String args[]) {
          new NewThread(); // 创建一个新线程
          try {
             for(int i = 5; i > 0; i--) {
                System.out.println("Main Thread: " + i);
                Thread.sleep(100);
             }
          } catch (InterruptedException e) {
             System.out.println("Main thread interrupted.");
          }
          System.out.println("Main thread exiting.");
       }
    }

    编译以上程序运行结果如下:

    Child thread: Thread[Demo Thread,5,main]
    Main Thread: 5
    Child Thread: 5
    Child Thread: 4
    Main Thread: 4
    Child Thread: 3
    Child Thread: 2
    Main Thread: 3
    Child Thread: 1
    Exiting child thread.
    Main Thread: 2
    Main Thread: 1
    Main thread exiting.

    【正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!下面有个“顶”字,你就顺手把它点了吧(要先登录CSDN账号哦 )】


    —–乐于分享,共同进步!
    —–更多文章请看:http://blog.csdn.net/duruiqi_fx


  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/hainange/p/6153819.html
Copyright © 2011-2022 走看看