Java中创建线程的两种方式

1.定义实现Runnable接口的线程类,步骤如下:

  (1)创建实现了Runnable接口的线程类Runner;

  (2)重写Runnable接口的run()方法,用于定义线程的运行体;(Runnable接口只有这一个方法)

  (3)实例化线程类Runner;

  (4)创建线程实例,并将线程类Runner的实例传递给它作为构造函数的参数;

  (5)启动线程;

   代码如下所示:

 1 public class TestThread {
 2     public static void main(String args[]) {
 3         Runner r = new Runner();    //3.实例化线程类Runner    
 4         Thread thread = new Thread(r); //4.创建线程实例,并将线程类Runner的实例传递给它作为构造函数的参数
 5         thread.start();    //5.启动线程
 6         
 7         for(int i=0; i<100; i++) { //主线程其他代码
 8             System.out.println("Main Thread:------" + i);
 9         }
10     }
11 }
12 
13 class Runner implements Runnable {  //1.创建实现了Runnable接口的线程类Runner
14     public void run() { //2.重写run方法,用于定义线程的运行体
15         for(int i=0; i<100; i++) {    
16             System.out.println("Runner1 :" + i);
17         }
18     }
19 }

 2. 定义一个继承自Thread类的子类,并重写其run方法

  (1)创建继承自Thread类的子类MyThread类;

  (2)重写其run方法,用于定义线程的运行体;

  (3)实例化线程子类MyThread ;

  (4)启动线程;

 1 public class TestThread {
 2     public static void main(String args[]) {
 3         MyThread myThread = new MyThread();    //3.实例化线程子类MyThread            
 4         myThread.start();    //4.启动线程
 5         
 6         for(int i=0; i<100; i++) { //主线程其他代码
 7             System.out.println("Main Thread:------" + i);
 8         }
 9     }
10 }
11 
12 class MyThread extends Thread {  //1.创建继承自Thread类的子类MyThread类
13     public void run() { //2.重写其run方法,用于定义线程的运行体
14         for(int i=0; i<100; i++) {    
15             System.out.println("Runner1 :" + i);
16         }
17     }
18 }

 注意:推荐使用实现Runnable接口的方式创建线程,原因:相对比较灵活,还可以实现其他接口,继承其他类

原文地址:https://www.cnblogs.com/tjudzj/p/4420922.html