1. 继承 Thread 类
继承 Thread 类,重写 run() 办法。
在主线程中创立 MyThread 类对象,调用 start() 办法启动线程。
public class ThreadDemo { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); } static class MyThread extends Thread { @Override public void run() { System.out.println("继承 Thread 创立线程"); } }
2. 实现 Runnable 接口
创立一个 MyRunnable 外部类实现 Runnable 接口,重写 run() 办法。
在创立 Thread 类对象时传入 MyRunnable 类对象。
也能够不独自写 Runnable 接口的实现类,间接应用 Lambda 表达式实现。
public class ThreadDemo { public static void main(String[] args) { //实现 Runnable 接口 Thread t1 = new Thread(new MyRunnable()); t1.start(); //间接应用 Lambda 缩写 new Thread(()->{ System.out.println("用 Lambda 缩写创立线程"); }).start(); } static class MyRunnable implements Runnable { @Override public void run() { System.out.println("实现 Runnable 接口创立线程"); } }}
3. 实现 Callable 接口
创立一个 MyCallable 外部类实现 Callable 接口,重写 call() 办法。
FutureTask 实现了 RunnableFuture,RunnableFuture 继承了 Runnable, Future。
意味着可通过 FutureTask 接管 Callable 中 call 办法的返回值。
并和 Runnable 一样,传入 Thread 中创立线程。
futureTask.get() 办法能够失去线程返回后果,然而该办法是阻塞的。
意味着如果 t1 线程始终在运算,main 线程须要始终期待 t1 的完结,拿到后果能力持续运行。
public class ThreadDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask futureTask = new FutureTask<>(new MyCallable()); Thread t1 = new Thread(futureTask); t1.start(); //如果 futureTask.get() 没失去后果,代码将始终等着 System.out.println(futureTask.get()); System.out.println("t1 线程执行实现"); } static class MyCallable implements Callable { @Override public Object call() { System.out.println("实现 Callable 接口创立线程"); return "Callable 返回后果"; } }}
4. 应用线程池创立
长处:
升高资源耗费。 通过反复利用已创立的线程升高线程创立和销毁造成的耗费。
进步响应速度。 当工作达到时,工作能够不须要等到线程创立就能立刻执行。
进步线程的可管理性。 如果无限度的创立线程,不仅会耗费系统资源,还会升高零碎的稳定性,通过线程池能够进行对立的调配,调优和监控。
public class ThreadDemo { public static void main(String[] args){ //创立固定 5 个线程的线程池 ExecutorService executorService = Executors.newFixedThreadPool(5); //用线程池执行 100 次工作 for (int i = 0; i < 100; i++) { executorService.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }); } }}