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

}
相关推荐
diving deep9 分钟前
springboot集成日志配置文件
java·spring boot·后端·logback
源码云商1 小时前
基于 SpringBoot + Vue 的海滨体育馆管理系统设计与实现
vue.js·spring boot·后端
Themberfue3 小时前
RabbitMQ ⑥-集群 || Raft || 仲裁队列
linux·运维·分布式·后端·rabbitmq·ruby
不争先.6 小时前
Pycharm和Flask的学习心得(4和5)
后端·python·flask
编程乐学(Arfan开发工程师)8 小时前
16、最佳实践-SpringBoot应用如何编写
java·spring boot·后端
fashia9 小时前
Java转Go日记(五十六):gin 渲染
开发语言·后端·golang·go·gin
养-乐多9 小时前
梳理Spring Boot中三种异常处理
java·spring boot·后端
Code哈哈笑9 小时前
【基于SpringBoot的图书购买系统】深度讲解 分页查询用户信息,分析前后端交互的原理
java·数据库·spring boot·后端·spring·交互
.生产的驴9 小时前
Vue3 数据可视化屏幕大屏适配 页面自适应 响应式 数据大屏 大屏适配
java·c++·vue.js·后端·信息可视化·前端框架·vue
源码云商10 小时前
基于 Spring Boot + Vue 的墙绘产品展示交易平台设计与实现【含源码+文档】
vue.js·spring boot·后端