创建线程的几种方式
1️⃣ 继承 Thread 类
继承 Thread 类创建线程的步骤为:
1)创建一个类继承Thread类,重写run()方法,将所要完成的任务代码写进run()方法中;
2)创建Thread类的子类的对象;
3)调用该对象的start()方法,该start()方法表示先开启线程,然后调用run()方法;- @Slf4j
- public class ExtendsThread {
- static class T extends Thread {
- @Override
- public void run() {
- log.debug("hello");
- }
- }
- public static void main(String[] args) {
- T t = new T();
- t.setName("t1");
- t.start();
- }
- }
复制代码 也可以直接使用Thread 类创建线程:- public static void main(String[] args) {
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- log.debug("hello");
- }
- }, "t1");
- }
复制代码 看看 Thread 类的构造器,Thread 类有多个构造器来创建需要的线程对象:- // Thread.java
- public Thread() {}
- public Thread(Runnable target) {}
- public Thread(String name) {}
- public Thread(Runnable target, String name) {}
- // 还有几个使用线程组创建线程的构造器,就不列举了
复制代码 2️⃣ Runnable 接口配合 Thread
实现 Runnable 接口创建线程的步骤为:
1)创建一个类并实现 Runnable 接口;
2)重写 run() 方法,将所要完成的任务代码写进 run() 方法中;
3)创建实现 Runnable 接口的类的对象,将该对象当做 Thread 类的构造方法中的参数传进去;
4)使用 Thread 类的构造方法创建一个对象,并调用 start() 方法即可运行该线程;- @Slf4j
- public class ImplRunnable {
- static class T implements Runnable {
- @Override
- public void run() {
- log.debug("hello");
- }
- }
- public static void main(String[] args) {
- Thread t1 = new Thread(new T(), "t1");
- t1.start();
- }
- }
复制代码 也可以写成这样:- public static void main(String[] args) {
- Runnable task = new Runnable() {
- @Override
- public void run() {
- log.debug("hello");
- }
- };
- Thread t2 = new Thread(task, "t2");
- t2.start();
- }
复制代码 Java 8 以后可以使用 lambda 精简代码(IDEA会有提示可将匿名内部类换成 Lambda 表达式):- public static void main(String[] args) {
- Runnable task = () -> log.debug("hello");
- Thread t2 = new Thread(task, "t2");
- t2.start();
- }
复制代码 查看一下 Runnable 接口的源码,可以看到 Runnable 接口中只有一个抽象方法 run(),这种只有一个抽象方法的接口会加上一个注解:@FunctionalInterface,那只要带有这个注解的接口就可以被Lambda表达式来简化。- @FunctionalInterface
- public interface Runnable {
- public abstract void run();
- }
复制代码 分析一下源码:
[code]public static void main(String[] args) { Runnable task = () -> log.debug("hello"); Thread t2 = new Thread(task, "t2"); t2.start();}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |