1、创建多线程
1.1、继承Thread类
package demo; /** * @description: demo01 * @author: liuyang * @create: 2021-08-24 21:40 */ public class Demo01 extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Demo01 myThread = new Demo01(); myThread.setName("my-thread-test"); myThread.start(); } }
1.2、实现Runnable接口
package demo; /** * @description: demo02 * @author: liuyang * @create: 2021-08-24 21:53 */ public class Demo02 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { // 方式1 Thread myThread1 = new Thread(new Demo02()); myThread1.setName("myThread1"); myThread1.start(); // 方式2-匿名内部类 Thread myThread2 = new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }); myThread2.setName("myThread2"); myThread2.start(); // 方式3--函数式编程 Thread myThread3 = new Thread(() -> { System.out.println(Thread.currentThread().getName()); }); myThread3.setName("myThread3"); myThread3.start(); } }