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

}
相关推荐
用户3600555790020 分钟前
Kestrel_VLLM - 34 · 批量 M 行:五个块、两种层型,与「退回去」的两个原语
后端
leo在掘金26 分钟前
25.5k Star 的 DeepInfer 怎么扛住3万亿参数
后端·架构
Agent世界38 分钟前
cookie 判据会撒谎:CDP 登录态保活的五个实测坑
后端·自动化运维
林小帅40 分钟前
【笔记】Prisma v7 + SQLite TS2305 及连锁 TS7006 问题
前端·javascript·后端
王中阳Go43 分钟前
你那条三跳链路的单跳超时,是按压测的 p95 定的,还是拍出来的?
人工智能·后端·架构
时光不老杰1 小时前
03 Netty 双通道长连接层
后端
136096757231 小时前
报错指的地方,往往不是坏的地方:47 次故障的定位方法
后端
Gopher_HBo1 小时前
cpuprof.go开关、缓冲区与记账
后端
特立独行的猫A3 小时前
13MB 单文件、一条命令变服务:把仓颉写的 cjh 内嵌进你的应用,当它的 AI 大脑
java·后端·python
IT_陈寒4 小时前
SpringBoot实战技巧总结
前端·人工智能·后端