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();
    }

}
相关推荐
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法8 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte9 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行10 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple10 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东10 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble10 小时前
springboot的核心实现机制原理
java·spring boot·后端
全栈老石11 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python