通过Callable接口实现多线程

通过Callable接口实现多线程

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"\t"+"come in");
        return 1024;
    }
}

public class CallableTest {

    public static void main(String[] args) throws Exception {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
        Thread thread = new Thread(futureTask, "T1");
        thread.start();

        Integer s1 = 100;
        Integer s2 = futureTask.get();
        System.out.println("result="+(s1+s2));
    }

}

输出结果:

T1 come in
result=1124

### Callable接口实现多线程 Callable接口是在JDK1.5版本被引入,用于提供一种能够在线程完成时返回结果的方法。相比Runnable接口而言,Callable允许有返回值,并可以抛出异常[^1]。 下面是一个简单的例子来展示如何使用`Callable<V>`接口创建并运行一个多线程程序: #### 创建一个实现Callable接口的类 ```java import java.util.concurrent.Callable; public class TaskWithResult implements Callable<String> { private String name; public TaskWithResult(String name){ this.name = name; } @Override public String call() throws Exception { Thread.sleep(200); // Simulate a delay due to task processing. return "Result of " + name; } } ``` 这段代码定义了一个名为`TaskWithResult`的类,它实现了`Callable<String>`接口。该类有一个参数化的构造函数接受任务名称作为输入,在调用其`call()`方法时模拟了一些处理延迟,并最终返回字符串形式的结果[^4]。 #### 使用ExecutorService提交任务并获取Future对象 为了执行上述自定义的任务,通常会借助于`ExecutorService`框架中的工具类如`Executors`工厂类来简化管理多个辅助线程的过程。这里展示了如何利用这些APIs: ```java import java.util.concurrent.*; public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException{ ExecutorService executor = Executors.newFixedThreadPool(2); TaskWithResult task1 = new TaskWithResult("task-1"); TaskWithResult task2 = new TaskWithResult("task-2"); Future<String> future1 = executor.submit(task1); Future<String> future2 = executor.submit(task2); System.out.println(future1.get()); // This will block until the result is available. System.out.println(future2.get()); executor.shutdown(); } } ``` 在这个示例中,首先通过`Executors.newFixedThreadPool(int nThreads)`创建了一个具有固定大小的工作池;接着分别实例化两个不同的`TaskWithResult`对象并将它们提交给工作池去异步执行;最后通过调用`future.get()`等待各个任务完成后取得相应的计算结果[^3]。 当涉及到大量短期任务时需要注意的是,频繁地创建和销毁线程可能会消耗大量的资源从而影响性能表现[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值