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

}
相关推荐
庞轩px1 小时前
第七篇:Spring扩展点——如何优雅地介入Bean的创建流程
java·后端·spring·bean·aware·扩展点
ltl1 小时前
Q/K/V 三件套:把 Bahdanau 抽象成一个公式
后端
千叶风行3 小时前
Text-to-SQL 技术设计与注意事项
前端·人工智能·后端
阿kun要赚马内4 小时前
后端数据操作组合:Pydantic与ORM
后端·python·orm·sqlalchemy
花米徐5 小时前
技术洞察精选 | 2026年4月28日 — 5月4日
后端·python·flask
阿维的博客日记5 小时前
Spring Cloud 为什么需要服务注册与发现中心这些东西?
后端·spring·spring cloud
笑而不语5 小时前
13|元数据过滤检索:UserContext 与按用户查知识
后端
用户095367515836 小时前
Go:浮点数如何进行比较?
后端·go
Zeus_6 小时前
如何更好的创建skill
后端
千云6 小时前
AI Coding 落地探索日志 · 初篇 · 启程记
后端·ai编程