创建线程的四种方法(Java)

目录

[一、继承 Thread类](#一、继承 Thread类)

二、实现Runnable接口

三、实现Callable接口

四、使用线程池


一、继承 Thread类

创建一个类 Thread 类,并重写run()方法,通过start()启动线程。以继承的方式创建的线程可以使用当前类来获取线程的名称、状态、优先级等相关信息,因为其继承了Thread类的相关方法。

java 复制代码
public class MyThread extends Thread{
 
    @Override
    public void run(){
        while(true){
            System.out.println(this.getName());
        }
    }
}

我们写一个main方法来测试:

java 复制代码
public class Main {
    public static void main(String[] args) {
        MyThread myThread=new MyThread();
        myThread.start();
    }
}

执行结果:

二、实现Runnable接口

Runnable接口定义了线程要执行的任务,可以在类中实现该接口来创建线程。在实现该接口后,需要创建Thread对象,并将实现了Runnable接口的类的实例作为构造函数参数传递给Thread对象。然后调用start()方法启动线程。

java 复制代码
//自定义类实现Runnable接口
public class RunnableTest implements Runnable{
    @Override
    public void run(){
        System.out.println("你好");
    }
}

我们写一个main方法来测试:

java 复制代码
public class Main {
    public static void main(String[] args) {
        RunnableTest runnableTest=new RunnableTest();
        Thread thread=new Thread(runnableTest);
        thread.start();
    }
}

运行结果:

三、实现Callable接口

Callable接口与Runnable接口类似,但是Callable接口的call()方法可以返回执行结果。在实现Callable接口后,需要使用ExecutorService来启动线程,ExecutorService.submit()方法可以启动Callable线程,并返回Future对象,可以使用该对象获取线程执行的结果。

haxe 复制代码
public class MyCallable implements Callable<Integer> {
    public Integer call() {
        // 线程要执行的任务
        return result;
    }
}

MyCallable c = new MyCallable();
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Integer> result = executorService.submit(c);
 

四、使用线程池

线程池是一种管理和复用线程的机制,它可以在应用程序中创建一组可重用线程,线程池中的线程可以重复使用,从而避免了频繁创建和销毁线程带来的性能问题。使用线程池可以在需要执行任务时,直接从线程池中取出空闲线程来执行任务。

java 复制代码
public class RunnableTest implements Runnable{
    @Override
    public void run(){
        System.out.println("你好");
    }
}


ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
    Runnable worker = new RunnableTest();
    executorService.execute(worker);
}
executorService.shutdown();
while (!executorService.isTerminated()) {
    // 等待所有任务完成
}

关于线程池的几种实现方法,我会在写在下一篇博客噢,希望大家多多支持噢🤗

相关推荐
yue00813 分钟前
C# 更改窗体样式
开发语言·c#
普通网友18 分钟前
C++中的适配器模式
开发语言·c++·算法
风闲121720 分钟前
Qt源码编译记录
开发语言·qt
Felix_XXXXL35 分钟前
mysql查看binlog日志
java·后端
leonardee39 分钟前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端
普通网友40 分钟前
C++中的委托构造函数
开发语言·c++·算法
珹洺1 小时前
Java-Spring入门指南(三十一)Android意图(Intent)
android·java·spring
Seven971 小时前
剑指offer-39、平衡⼆叉树
java
月上柳青1 小时前
OpenWrt系统上配置batman-adv快速开始与配置详解
开发语言·mysql·php
全栈陈序员1 小时前
基于Rust 实现的豆瓣电影 Top250 爬虫项目
开发语言·爬虫·rust