创建线程的方式

  1. 继承Thread类创建线程类
    定义Thread的子类,重写run方法,run方法定义线程的执行逻辑。创建该类的实例,并执行start()方法。
    示例:
public class TestThread {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("Main函数执行完成,执行线程为:"+Thread.currentThread());
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("当前执行线程:"+ Thread.currentThread() + ",MyThread run...");
    }
}

执行结果:

Main函数执行完成,执行线程为:Thread[main,5,main]
当前执行线程:Thread[Thread-0,5,main],MyThread run...
  1. 通过Runnable接口创建线程类
    定义Runnable接口的实现类,重写run方法,创建该类的实例,并将其作为参数创建Thread类的实例
    示例:
public class TestThread {

    public static void main(String[] args) {
        testRunnable();
        System.out.println("Main函数执行完成,执行线程为:"+Thread.currentThread());
    }

    private static void testRunnable() {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}
class MyRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("当前执行线程:"+ Thread.currentThread() + ",MyRunnable run...");
    }
}

执行结果:


  1. 通过Callable和Future创建线程
  • 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
  • 创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。
  • 使用FutureTask对象作为Thread对象的target创建并启动新线程。
  • 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。
    示例:
public class TestThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        testCallable();
        System.out.println("Main函数执行完成,执行线程为:"+Thread.currentThread());
    }


    private static void testCallable() throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        Thread thread = new Thread(futureTask);
        thread.start();
        String threadResult = futureTask.get();
        System.out.println("MyCallable执行返回结果为:" + threadResult);
    }
}


class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("当前执行线程:"+ Thread.currentThread() + ",MyCallable run...");
        return "执行完成";
    }
}

执行结果:

当前执行线程:Thread[Thread-0,5,main],MyCallable run...
MyCallable执行返回结果为:执行完成
Main函数执行完成,执行线程为:Thread[main,5,main]
  1. ExecutorService
    ExecutorService是Java提供的线程池,可以需要使用线程的时候可以通过ExecutorService获取线程。它可以有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞,同时提供定时执行、定期执行、单线程、并发数控制等功能。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容