一、extends Thread

编写类并extends Thead类,Override run()

实例化编写的类,执行方法 start()

 

public class Main {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start(); // 启动新线程
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}

二、implements Runnable

编写类并implements Runnable接口,Override run()

实例化并执行方法 start()

与上一方法区别是无需继承Thread类

 

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start(); // 启动新线程
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("start new thread!");
    }
}