zoukankan      html  css  js  c++  java
  • 通过继承Thread类实现多线程

     1 package testBlog;
     2 
     3 class MyThread extends Thread{
     4     String name;
     5     
     6     MyThread(String name){
     7         this.name = name;
     8     }//用构造器给线程起名
     9     
    10     public void run() {//这里要记得覆写run()方法
    11         for(int x = 0;x<20;x++) {
    12             System.out.println(this.name+"--->"+x);
    13         }
    14     }
    15     
    16 }
    17 public class Test{
    18     public static void main(String[] args) {
    19         MyThread mt1 = new MyThread("线程A");
    20         MyThread mt2 = new MyThread("线程B");
    21         MyThread mt3 = new MyThread("线程C");
    22         
    23         mt1.run();//两种方式启动线程
    24         mt2.start();//start()方法默认和run()一样
    25         mt3.start();
    26         //最终每次输出的内容不一样.
    27     }
    28 }

     注意:但在这里不建议使用run()方法来启动线程,可能会导致线程无法启动.也就是说,通过继承Thread类创建的线程,最好最好使用start()方法来启动.

  • 相关阅读:
    48-最长不含重复字符的子字符串
    51-数组中的逆序对
    字符串的排列
    二叉树转链表
    求根
    构造二叉树
    二叉树中序遍历
    反转链表系列
    斐波那契系列
    f.lux
  • 原文地址:https://www.cnblogs.com/ssC2H4/p/8186290.html
Copyright © 2011-2022 走看看