Java创建线程的四种方法

继承Thread类

java 复制代码
public class MyThread extends Thread {

    static int count = 0;
    @Override
    public void run() {
        System.out.println(count++);
    }

    public static void main(String[] args) {
        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();

        myThread1.start();
        myThread2.start();
    }

}

实现runnable接口

java 复制代码
public class MyRunnable implements Runnable{

    static int count = 0;

    public void run() {
        System.out.println(count++);
    }

    public static void main(String[] args) {

        MyRunnable myRunnable = new MyRunnable();

        Thread myRunnable1 = new Thread(myRunnable);
        Thread myRunnable2 = new Thread(myRunnable);

        myRunnable1.start();
        myRunnable2.start();
    }
    
}

实现callable接口

arduino 复制代码
public class MyCallable implements Callable<String> {

     static int count;

    public String call() throws Exception {

        System.out.println("count:"+count++);

        return String.valueOf(count);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();

        FutureTask<String> stringFutureTask1 = new FutureTask<String>(myCallable);
        FutureTask<String> stringFutureTask2 = new FutureTask<String>(myCallable);

        Thread thread1 = new Thread(stringFutureTask1);
        Thread thread2 = new Thread(stringFutureTask2);

        thread1.start();

        System.out.println(stringFutureTask1.get());

        thread2.start();

        System.out.println(stringFutureTask2.get());

    }

}

线程池创建

typescript 复制代码
public class MyExecutors implements Runnable{
    static int count = 0;

    public void run() {
        System.out.println(count++);
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);

        pool.submit(new MyExecutors());
        pool.submit(new MyExecutors());

        pool.shutdown();
    }

}
相关推荐
程序猿小蒜2 小时前
基于springboot的车辆管理系统设计与实现
java·数据库·spring boot·后端·spring·oracle
90后的晨仔2 小时前
Java后端开发:从零构建企业级应用的完整架构与技术栈详解
后端
我命由我123453 小时前
Spring Cloud - Spring Cloud 声明式接口调用(Fiegn 声明式接口调用概述、Fiegn 使用)
java·后端·spring·spring cloud·微服务·架构·java-ee
canonical_entropy3 小时前
领域驱动设计(DDD)中聚合根的最主要职责真的是维护一致性吗?
后端·架构·领域驱动设计
AntBlack3 小时前
不当韭菜 : 好像真有点效果 ,想藏起来自己用了
前端·后端·python
橙子家4 小时前
Serilog 日志库的简介
后端
间彧4 小时前
Java线程池深度实战:不同场景下的最优选择与性能优化
后端
间彧4 小时前
CompletableFuture与线程池:并发编程的双剑合璧
后端
间彧4 小时前
在实际项目中,如何根据任务类型(CPU/IO密集型)设计不同的线程池策略?
后端
golang学习记4 小时前
Go slog 日志打印最佳实践指南
开发语言·后端·golang