整理不易求关注[送心]
通过继承 Thread 类
继承Thread类,重新run方法
public class Test extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Test test1 = new Test(); Test test2 = new Test(); test1.start(); test2.start(); }}
通过实现 Runnable 接口
实现Runnable接口,重写run方法
public class Test implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { Thread thread1 = new Thread(new Test()); Thread thread2 = new Thread(new Test()); thread1.start(); thread2.start(); }}
通过实现 Callable 接口
通过实现Callable接口,重写call方法,配合FutureTask,可以得到异步执行的结果。
public class Test implements Callable { @Override public Object call() throws Exception { return Thread.currentThread().getName(); } public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask futureTask = new FutureTask(new Test()); Thread thread = new Thread(futureTask,”线程名称”); thread.start(); // 得到异步执行结果 System.out.println(futureTask.get()); }}
通过Lambda表达式方式
直接使用Lambda表达式方式创建多线程,不需要继承或者实现类。(看起来很酷[绿帽子])
public class Test { public static void main(String[] args) { Runnable runnable = () -> { System.out.println(Thread.currentThread().getName()); }; new Thread(runnable).start(); }}
通过内部类方式
public class Test { public static void main(String[] args) { // 1. new Thread() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }.start(); // 2. new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }).start(); // 3. new Thread(()->{ System.out.println(Thread.currentThread().getName()); }).start(); }}
通过线程池方式
提供四种创建线程池的方式:
public class Test { public static void main(String[] args) { // 定长线程池,固定线程总数 ExecutorService executorService1 = Executors.newFixedThreadPool(10); // 可缓存线程池,无限大,如果线程池没有可用线程就会自动创建,有的话就自动利用起来 ExecutorService executorService2 = Executors.newCachedThreadPool(); // 单线程池 ExecutorService executorService3 = Executors.newSingleThreadExecutor(); // 调度线程池 ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); }}