通过继承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()方法来启动.

posted on 2018-01-03 23:00  三盛乙烯  阅读(739)  评论(0编辑  收藏  举报

导航