继承Thread类
package com.mashibing.juc.c_000_threadbasic;import java.util.concurrent.*;public class T02_HowToCreateThread {static class MyThread extends Thread {@Overridepublic void run() {System.out.println("Hello MyThread!");}}//启动线程的5种方式public static void main(String[] args) throws Exception {new MyThread().start();}}
实现Runnable接口
相比继承Thread类,这种实现Runnable接口的方式更合适 因为一个类实现Runnable接口后还可以从其他类去继承 但一个类继承了Thread类之后不能再从其他类继承
package com.mashibing.juc.c_000_threadbasic;import java.util.concurrent.*;public class T02_HowToCreateThread {static class MyRun implements Runnable {@Overridepublic void run() {System.out.println("Hello MyRun!");}}//启动线程的5种方式public static void main(String[] args) throws Exception {new Thread(new MyRun()).start();}}
使用Lambda表达式
package com.mashibing.juc.c_000_threadbasic;import java.util.concurrent.*;public class T02_HowToCreateThread {//启动线程的5种方式public static void main(String[] args) throws Exception {new Thread(() -> {System.out.println("Hello Lambda!");}).start();}}
