线程的创建方式
继承 Thread
- 创建一个继承 Thread 类的子类。
- 重写 Thread 类的 run() 方法。
- 在 run() 方法中编写线程要执行的任务。
- 创建 Thread 子类的对象。
- 调用 Thread 子类对象的 start() 方法来启动线程。
public class Demo { static class MyThread extends Thread { @Override public void run() { System.out.println(">>>> run "); } } public static void main(String[] args) { new MyThread().start(); } }
实现 Runnable
接口
- 创建一个实现 Runnable 接口的类。
- 在 Runnable 接口的 run() 方法中编写线程要执行的任务。
- 创建 Runnable 接口的实现类的对象。
- 将 Runnable 接口的实现类的对象传递给 Thread 类的构造方法来创建 Thread 对象。
- 调用 Thread 对象的 start() 方法来启动线程。
package org.example.create; public class Demo1 { static class MyThread1 implements Runnable { @Override public void run() { System.out.println(">>>>> 2. 实现Runnable接口"); } } public static void main(String[] args) throws Exception { new MyThread1().run(); System.out.println("end"); } }
实现 Callable
接口
package org.example.create; import java.util.concurrent.Callable; public class Demo2 { static class MyThread implements Callable<Void> { @Override public Void call() throws Exception { System.out.println("3. 实现 Callable "); return null; } } public static void main(String[] args) throws Exception { new MyThread().call(); System.out.println("end"); } }
使用 Lambda
package org.example.create; public class Demo3 { public static void main(String[] args) throws Exception { new Thread(()->{ System.out.println("4. 使用 lambda 表达式"); }).run(); System.out.println("end"); } }
使用线程池
package org.example.create; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Demo4 { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); // 创建Runnable对象 Runnable runnable = () -> { // 线程的执行逻辑 System.out.println(Thread.currentThread().getId() + "线程执行逻辑"); }; // 提交任务给线程池 for (int i = 0; i < 50; i++) { executor.submit(runnable); } // 关闭线程池 executor.shutdown(); } }
线程创建相关的 jdk
源码
Thread
类
package java.lang; public class Thread implements Runnable { /* Make sure registerNatives is the first thing <clinit> does. */ private static native void registerNatives(); static { registerNatives(); } }
Runnable
函数接口
package java.lang; /** The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped. In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class. Since: 1.0 See Also: Thread, java.util.concurrent.Callable **/ @FunctionalInterface public interface Runnable { /** * When an object implementing interface {@code Runnable} is used * to create a thread, starting the thread causes the object's * {@code run} method to be called in that separately executing * thread. * <p> * The general contract of the method {@code run} is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
Callable<V>
函数接口
package java.util.concurrent; /** A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call. The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception. The Executors class contains utility methods to convert from other common forms to Callable classes. Since: 1.5 See Also: Executor Author: Doug Lea Type parameters: <V> – the result type of method call **/ @FunctionalInterface public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
executors
package java.util.concurrent; /** Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods: Methods that create and return an ExecutorService set up with commonly useful configuration settings. Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings. Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible. Methods that create and return a ThreadFactory that sets newly created threads to a known state. Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable. Since: 1.5 Author: Doug Lea **/ public class Executors {}