Java中创建线程的多种方式实例

目录

1、普通Thread创建

2、实现Runnable接口创建线程

3、匿名方式创建

4、使用Lambda表达式创建线程

5、实现Callable接口创建线程

6、线程池方式

7、线程工具类


在Java中创建线程的方式有多种,以下是几种常见的创建线程的方式,选择哪种方式取决于具体的需求和设计。需要注意的是,在使用多线程时,要确保线程安全,避免出现并发问题。

1、普通Thread创建

//继承创建线程
    static class NewThread extends Thread {
        @Override
        public void run() {
            System.out.println("继承Thread创建线程-1 = " + DateUtils.getNowTime());
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("继承Thread创建线程-2 = " + DateUtils.getNowTime());

        }
    }

启动线程

        //普通Thread创建
        NewThread nt = new NewThread();
        nt.start();

2、实现Runnable接口创建线程

// 实现Runnable接口创建线程
    static class NewRunnable implements Runnable {
        @Override
        public void run() {

            System.out.println("实现Runnable接口-3 = " + DateUtils.getNowTime());

            //等待
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("实现Runnable接口-4 = " + DateUtils.getNowTime());
        }
    }

启动线程

        //普通Runnable创建
        NewRunnable nr = new NewRunnable();
        Thread t = new Thread(nr);
        t.start();

3、匿名方式创建

        //匿名Thread创建
        Thread t1 = new Thread(new Thread() {
            @Override
            public void run() {
                System.out.println("匿名Thread" + DateUtils.getNowTime());
            }
        });
        t1.start();


        //匿名Runnable创建
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名Runnable创建 = " + DateUtils.getNowTime());
            }
        });
        t2.start();

4、使用Lambda表达式创建线程


        //使用Lambda表达式创建线程
        Thread t3 = new Thread(() -> System.out.println("Lambda表达式创建1 = " + DateUtils.getNowTime()));
        t3.start();

        Runnable r = () -> {
            System.out.println("Lambda表达式创建2 = " + DateUtils.getNowTime());
        };
        Thread t4 = new Thread(r);
        t4.start();

5、实现Callable接口创建线程

在使用这个 Callable创建线程的时候,是有返回值的线程调用

    /**
     * 实现Callable接口创建线程
     * 是有返回值的线程调用
     */
    static class NewCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("实现Callable接口创建线程-5 = " + DateUtils.getNowTime());
            Thread.sleep(3000);
            System.out.println("实现Callable接口创建线程-6 = " + DateUtils.getNowTime());
            return "Callable接口创建线程";
        }
    }

启动线程

        //调用callable创建线程
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "callable创建线程";
            }
        };
        //FutureTask<String> futureTask = new FutureTask<>(callable);

        // 调用NewCallable()
        FutureTask<String> futureTask = new FutureTask<>(new NewCallable());
        Thread t5 = new Thread(futureTask);
        t5.start();

6、线程池方式

创建线程池的时候,可以定义线程池的大小,线程池中可以执行多个任务。若需要获取异步执行任务的返回值的话,使用submit方法;若是让一个任务在线程池中异步执行,使用execute方法即可。
//         相同点:
//         submit和execute方法均可以像线程池中提交一个任务,让线程池来异步执行这个任务
//         不同点:
//         submit可以接受Runnable和Callable任务,但execute只能接受Runnable任务;
//         submit方法的返回值是一个Future,而execute方法的返回值是void;
//         对于异常的处理,使用submit方式提交的任务若在执行的过程中抛出了异常的话,异常信息在控制台中看不到,需要通过Future.get方法来获取这个异常;
//         使用execute方式提交的任务若在执行的过程中出现异常的话,异常信息会被打印到控制台;

        // 创建一个10个大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 提交任务到线程池、创建一个线程
        executorService.submit(new NewRunnable());
        // 执行一个任务
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程池创建线程 = " + DateUtils.getNowTime());
            }
        });
        // 关闭线程池
        executorService.shutdown();

7、线程工具类


import com.terra.utils.DateUtils;

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

public class T1 {

    public static void main(String[] args) {

        //普通Thread创建
        NewThread nt = new NewThread();
        nt.start();

        //匿名Thread创建
        Thread t1 = new Thread(new Thread() {
            @Override
            public void run() {
                System.out.println("匿名Thread" + DateUtils.getNowTime());
            }
        });
        t1.start();

        //普通Runnable创建
        NewRunnable nr = new NewRunnable();
        Thread t = new Thread(nr);
        t.start();

        //匿名Runnable创建
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名Runnable创建 = " + DateUtils.getNowTime());
            }
        });
        t2.start();

        //使用Lambda表达式创建线程
        Thread t3 = new Thread(() -> System.out.println("Lambda表达式创建1 = " + DateUtils.getNowTime()));
        t3.start();

        Runnable r = () -> {
            System.out.println("Lambda表达式创建2 = " + DateUtils.getNowTime());
        };
        Thread t4 = new Thread(r);
        t4.start();


        //调用callable创建线程
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "callable创建线程";
            }
        };
        //FutureTask<String> futureTask = new FutureTask<>(callable);

        // 调用NewCallable()
        FutureTask<String> futureTask = new FutureTask<>(new NewCallable());
        Thread t5 = new Thread(futureTask);
        t5.start();


//         相同点:
//         submit和execute方法均可以像线程池中提交一个任务,让线程池来异步执行这个任务
//         不同点:
//         submit可以接受Runnable和Callable任务,但execute只能接受Runnable任务;
//         submit方法的返回值是一个Future,而execute方法的返回值是void;
//         对于异常的处理,使用submit方式提交的任务若在执行的过程中抛出了异常的话,异常信息在控制台中看不到,需要通过Future.get方法来获取这个异常;
//         使用execute方式提交的任务若在执行的过程中出现异常的话,异常信息会被打印到控制台;

        // 创建一个10个大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 提交任务到线程池、创建一个线程
        executorService.submit(new NewRunnable());
        // 执行一个任务
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程池创建线程 = " + DateUtils.getNowTime());
            }
        });
        // 关闭线程池
        executorService.shutdown();


    }

    //继承创建线程
    static class NewThread extends Thread {
        @Override
        public void run() {
            System.out.println("继承Thread创建线程-1 = " + DateUtils.getNowTime());
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("继承Thread创建线程-2 = " + DateUtils.getNowTime());

        }
    }

    // 实现Runnable接口创建线程
    static class NewRunnable implements Runnable {
        @Override
        public void run() {

            System.out.println("实现Runnable接口-3 = " + DateUtils.getNowTime());

            //等待
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("实现Runnable接口-4 = " + DateUtils.getNowTime());
        }
    }

    /**
     * 实现Callable接口创建线程
     * 是有返回值的线程调用
     */
    static class NewCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("实现Callable接口创建线程-5 = " + DateUtils.getNowTime());
            Thread.sleep(3000);
            System.out.println("实现Callable接口创建线程-6 = " + DateUtils.getNowTime());
            return "Callable接口创建线程";
        }
    }

    // 使用线程池创建线程
    static class NewThreadPool {
        public static void main(String[] args) {
            // 创建大小2个任务的线程池
            ExecutorService executorService = Executors.newFixedThreadPool(2);
            // 提交任务
            executorService.submit(new NewRunnable());
            executorService.submit(new NewCallable());
            // 关闭线程池
            executorService.shutdown();
        }
    }


}

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值