java中实现多线程的三种方式(有/无返回值)

本文介绍了Java中实现多线程的三种方法:继承Thread类、实现Runnable接口和实现Callable接口。对比了不同方法的特点,并通过示例代码展示了如何创建线程、线程池以及获取线程返回值。

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

实现多线程有3种方法:继承Thread类、实现Runnable接口、实现Callable接口(第三种变化可以参考http://blog.youkuaiyun.com/aboy123/article/details/38307539)

一、继承Thread类

public class TestThread  extends Thread{

public void run(){

System.out.print(“启动线程”);

}

public static void main(String args[]){

Thread th=new Thread();

th.start();

}

}

二、实现Runnable接口

public class TestRunnable implements Runnable{

public void run(){

System.out.print(“启动线程”);

}

public static void main(String args[]){

TestRunnable tb=new TestRunnable();

Thread th=new Thread(tb);

th.run();

}

}

三、实现Callable接口

package test.querySystem.util;


import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//不能在public 类中实现Callable接口
class TestResultThread implements Callable<String>{
private int id;
//有参数构造方法
public TestResultThread(int id){
this.id=id;
}
@Override
public String call() throws Exception {
return “线程任务返回值”+id;
}
}
public class TestThreadCallnable {
public static void main(String args[]) throws InterruptedException, ExecutionException{
//创建线程池
ExecutorService exec=Executors.newCachedThreadPool();
//创建线程容器
ArrayList<Future<String>> result=new ArrayList<Future<String>>();
//执行任务后返回结果,假如只有10个线程
for(int i=0;i<10;i++){
Future<String> f=exec.submit(new TestResultThread(i));
result.add(f);
}
//遍历执行完成后的线程
for(Future<String> ft:result){
//判断是否执行完成
if(ft.isDone()){
System.out.println(“完成的线程:”+ft.get());
}else{
System.out.println(“未完成的线程:”+ft);
}
}
//关闭线程池
exec.shutdown();
}
}

注意:1、如果不需要返回值,最好使用Runnable接口

    2、如果Executor后台线程池还没有完成,那么这调用返回Future对象的get()方法,会阻塞直到计算完成。

            3、Callable规定Call()方法,而Runnable规定run()方法

    4、杀死进程最好就在类里面调用destroy()方法;不要实例化后再杀死!因为不知道线程到底什么时候结束!

Java实现多线程方式主要有以下几种: 1. 继承`Thread`类 2. 实现`Runnable`接口 3. 实现`Callable`接口并使用`FutureTask` 4. 使用线程池 下面是每种方式的代码示例及解释。 ### 1. 继承`Thread`类 ```java class MyThread extends Thread { public void run() { System.out.println("Thread is running."); } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } } ``` **解释**: 这里我们创建了一个继承自`Thread`的类,并重写了`run()`方法。通过调用`start()`方法来启动线程,这会自动调用`run()`方法。 ### 2. 实现`Runnable`接口 ```java class MyRunnable implements Runnable { public void run() { System.out.println("Runnable task is running."); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动线程 } } ``` **解释**: `Runnable`接口只有一个`run()`方法。我们将实现了`Runnable`接口的对象传递给`Thread`类的构造函数,然后启动线程。 ### 3. 实现`Callable`接口并使用`FutureTask` ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; class MyCallable implements Callable<Integer> { public Integer call() throws Exception { return 123; // 回一个整数 } } public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable()); Thread thread = new Thread(futureTask); thread.start(); System.out.println("Result: " + futureTask.get()); // 获取返回值 } } ``` **解释**: `Callable`与`Runnable`类似,但可以回结果并且可以抛出异常。这里我们使用了`FutureTask`来包装`Callable`任务,并通过`get()`方法获取任务执行结果。 ### 4. 使用线程池 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MyRunnableTask implements Runnable { public void run() { System.out.println("Task is running in thread pool."); } } public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); // 创建固定大小为2的线程池 for (int i = 0; i < 5; i++) { executor.submit(new MyRunnableTask()); // 提交任务 } executor.shutdown(); // 关闭线程池 } } ``` **解释**: 线程池是一种管理多个线程的机制,它可以重复利用已创建的线程来执行后续的任务。这里我们使用了`Executors.newFixedThreadPool(int nThreads)`来创建一个固定大小的线程池。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值