创建线程

方式1 继承Thread类

class MyThread01 extends Thread {
    @Override
    public void run() {
        System.out.println("继承Thread类");
    }

    public static void main(String[] args) {
        new MyThread01().start();//启动线程
    }
}

方式2 实现Runnable接口

class MyThread02 implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable接口");
    }

    public static void main(String[] args) {
        MyThread02 myThread02 = new MyThread02();
        Thread thread = new Thread(myThread02);
        thread.start();//启动线程
    }
}

方式3 实现Callable接口

class MyThread03 implements Callable<String> {
    @Override
    public String call() throws Exception {
        return "实现Callable接口 - 有返回值";
    }

    public static void main(String[] args) {
        MyThread03 myThread03 = new MyThread03();
        FutureTask<String> futureTask = new FutureTask<>(myThread03);
        Thread thread = new Thread(futureTask);
        thread.start();// 启动线程
        try {
            System.out.println("线程返回值: " + futureTask.get());// 获取返回值
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

ThreadPool线程池

Java通过Executors提供四种线程池,分别为:

  1. newCachedThreadPool 缓存线程池,灵活回收空闲线程。
  2. newFixedThreadPool 定长线程池,可控制线程最大并发数,超出线程在队列中等待。
  3. newScheduledThreadPool 定长线程池,支持定时及周期性任务执行。
  4. newSingleThreadExecutor 单线程池,用唯一的工作线程来执行任务。

常用方法:

  • execute() 添加任务
  • submit() 提交任务
  • shutdown() 关闭线程池
  • shutdownNow() 立即关闭线程池
class MyThread04 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 被调用");
    }

    public static void main(String[] args) {
        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();// 缓存线程池
        for (int i = 0; i < 10; i++) {
            executorService.execute(new MyThread04());//提交线程任务
        }
        executorService.shutdown();//关闭线程池

        ExecutorService executorService2 = Executors.newFixedThreadPool(5);// 定长线程池
        List<Future<String>> futureList = new ArrayList<>();//存储任务
        for (int i = 0; i < 5; i++) {
            MyThread03 myThread03 = new MyThread03();
            Future<String> future = executorService2.submit(myThread03);
            futureList.add(future);
        }
        
        for (int i = 0; i < 5; i++) {
            Future<String> future = futureList.get(i);
            try {
                System.out.println("result: " + future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService2.shutdown();
    }
}

版权声明:本文为linyufeng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/linyufeng/p/9656178.html