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

}
相关推荐
JaguarJack42 分钟前
Whim 是什么?一门把 PHP 被否决的设想真跑起来的实验语言
后端·php·服务端
明月_清风1 小时前
MHS:AI Agent 开始连接物理世界
人工智能·后端·网络协议
ssshooter1 小时前
Node.js 天生就是异步的,为什么还要消息队列?
javascript·后端·面试
福兮说1 小时前
Gin 项目里的错误处理:让 Controller 不必知道错误是怎么来的
后端·go·gin·架构设计
n8n2 小时前
Spring AI Alibaba Graph 实战:用图编排复杂业务,替代硬编码,支持分支、并行与人工确认
后端
Lyy2 小时前
DevOps平台 — 第十一篇:工作项的设计与实现
后端·devops
用户526835677902 小时前
Alertmanager 的告警怎么“喊“出来:Webhook 到声光语音终端的路由与抑制设计
后端
衝鋒壹号2 小时前
鸿蒙 PC 能跑 Docker 吗?一次从安装失败到成功运行的实测记录
后端·harmonyos
用户8181870627462 小时前
第27章 消息丢失/重复消费的全链路排查(生产者→Broker→消费者)
java·后端
程序员cxuan2 小时前
ChatGPT 开启无限 token
人工智能·后端·程序员