如何创建、启动 Java 线程?

Java 中有 4 种常见的创建线程的方式。

一、重写 Thread 类的 run() 方法。

    表现形式有两种:1)new Thread 对象匿名重写 run() 方法

package constxiong.concurrency.a006;

 /**
  * new Thread 对象匿名重写 run() 方法,启动线程
  * @author ConstXiong
  */
public class TestNewThread {
    
    public static void main(String[] args) {
        //创建线程 t, 重写 run() 方法
        new Thread("t") {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println("thread t > " + i);
                }
            }
        }.start();
    }

}

执行结果

thread t > 0
thread t > 1
thread t > 2

                                 2)继承 Thread 对象,重写 run() 方法

package constxiong.concurrency.a006;

/**
 * 继承 Thread 类,重写 run() 方法
 * @author ConstXiong
 */
public class TestExtendsThread {
    
    public static void main(String[] args) {
        new ThreadExt().start();
    }

}

//ThreadExt 继承 Thread,重写 run() 方法
class ThreadExt extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("thread t > " + i);
        }
    }
    
}

执行结果

thread t > 0
thread t > 1
thread t > 2

二、实现 Runnable 接口,重写 run() 方法。

    表现形式有两种:1)new Runnable 对象,匿名重写 run() 方法

package constxiong.concurrency.a006;

/**
 * new Runnalbe 对象匿名重写 run() 方法,启动线程
 * @author ConstXiong
 */
public class TestNewRunnable {

    public static void main(String[] args) {
        newRunnable();
    }
    
    public static void newRunnable() {
        //创建线程 t1, 重写 run() 方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println("thread t1 > " + i);
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1").start();
                
        //创建线程 t2, lambda 表达式设置线程的执行代码
        //JDK 1.8 开始支持 lambda 表达式
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                System.out.println("thread t2 > " + i);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2").start();
    }
}

执行结果

thread t1 > 0
thread t2 > 0
thread t1 > 1
thread t2 > 1
thread t1 > 2
thread t2 > 2

                                 2)实现 Runnable 接口,重写 run() 方法

package constxiong.concurrency.a006;

/**
 * 实现 Runnable 接口,重写 run() 方法
 * @author ConstXiong
 */
public class TestImplRunnable {

    public static void main(String[] args) {
        new Thread(new RunnableImpl()).start();
    }
}

///RunnableImpl 实现 Runnalbe 接口,重写 run() 方法
class RunnableImpl implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("thread t > " + i);
        }
    }
    
}

执行结果

thread t > 0
thread t > 1
thread t > 2

三、实现 Callable 接口,使用 FutureTask 类创建线程

package constxiong.concurrency.a006;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 实现 Callable 接口,使用 FutureTask 类创建线程
 * @author ConstXiong
 */
public class TestCreateThreadByFutureTask {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //通过构造 FutureTask(Callable callable) 构造函数,创建 FutureTask,匿名实现接口 Callable 接口
        FutureTask<String> ft = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "ConstXiong";
            }
        });
        
        //Lambda 方式实现
//        FutureTask<String> ft = new FutureTask<String>(() ->  "ConstXiong");
        
        new Thread(ft).start();
        System.out.println("执行结果:" + ft.get());
    }
}

执行结果

执行结果:ConstXiong

四、使用线程池创建、启动线程

package constxiong.concurrency.a006;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池的方式启动线程
 * @author ConstXiong
 */
public class TestCreateThreadByThreadPool {

    public static void main(String[] args) {
        // 使用工具类 Executors 创建单线程线程池
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        //提交执行任务
        singleThreadExecutor.submit(() -> {System.out.println("单线程线程池执行任务");});
        //关闭线程池
        singleThreadExecutor.shutdown();
    }
}

执行结果

单线程线程池执行任务

PS:这边只是简单的使用示例,至于 Runnable 接口和 Callable 接口的区别、线程池的使用,后面详细探索。


 来一道刷了进BAT的面试题?

原文地址:https://www.cnblogs.com/ConstXiong/p/11680343.html