java中创建线程有两种方式,一是继承Thread线程类,二是实现Runnable接口。
继承Thread线程类
继承类必须重写run()方法,这是新线程的入口点。它也必须调用start()方法才能执行。
实例
// 通过继承 Thread 创建线程 class MyThread extends Thread { MyThread() { //构造函数 System.out.println("孩子线程运行."); start(); // 开始线程 } // 线程入口 public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("孩子线程: " + i); // 让线程休眠一会 Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("孩子线程中断."); } System.out.println("退出孩子线程."); } } public class Test { public static void main(String args[]) { new MyThread(); // 创建一个新线程 try { for(int i = 5; i > 0; i--) { System.out.println("主线程: " + i); Thread.sleep(100); } } catch (InterruptedException e) { System.out.println("主线程中断."); } System.out.println("主线程退出."); } }实现Runnable接口
通过实现Runnable接口来创建线程是最简单的一种方式
为了实现Runnable,一个类只需要重写一个方法调用run()
// 创建一个新的线程 class MyThread implements Runnable { Thread t; MyThread() { // 创建新线程 t = new Thread(this, "Demo Thread"); System.out.println("孩子线程的名字: " + t); t.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("孩子线程中断."); } System.out.println("孩子线程结束."); } } public class Test { public static void main(String args[]) { new MyThread(); // 创建一个新线程 try { for(int i = 5; i > 0; i--) { System.out.println("主线程: " + i); Thread.sleep(100); } } catch (InterruptedException e) { System.out.println("主线程中断."); } System.out.println("主线程结束."); } }优缺点比较
采用继承Thread类方式:
(1)优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
(2)缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
采用实现Runnable接口方式:
(1)优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标(target)对象,所以非常适合多个相同线程来处理同一份资源的情况。
(2)缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。
(1)优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
(2)缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
采用实现Runnable接口方式:
(1)优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标(target)对象,所以非常适合多个相同线程来处理同一份资源的情况。
(2)缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。