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

本文介绍了Java中通过继承Thread类、实现Runnable接口、Callable接口以及使用线程池进行多线程编程的方法。重点讲解了每种方式的创建和使用,以及线程池在复用和性能优化中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、继承 Thread类

二、实现Runnable接口

三、实现Callable接口

四、使用线程池


一、继承 Thread类

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

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

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

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

执行结果:

二、实现Runnable接口

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

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

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

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对象,可以使用该对象获取线程执行的结果。

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

四、使用线程池

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

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()) {
    // 等待所有任务完成
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

马可波罗.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值