java 多线程给Callable传递参数

通过实现Callable接口,实现多线程程序时发现, call方法为@Override的无法直接在方法上传递参数,在网上找到了解决办法,通过构造方法传递参数放上代码

 private int taskNum;

    private String ip;

    private int port;

    public VerifyProxy(int taskNum, String ip, int port) {
        this.taskNum = taskNum;
        this.ip=ip;
        this.port=port;
    }

    /**
     * 验证代理ip是否可用
     * @return
     * @throws Exception
     */
    @Override
    public Object call() throws Exception {
        try {
            System.out.println(ip+port);
            Jsoup.connect("https://www.baidu.com")
                    .timeout(10 * 1000)
                    .proxy(ip, port)
                    .get();
            logger.info("该代理可用地址为{}{}",ip,port);
            return taskNum +"true" ;
        } catch (Exception e) {
            logger.info("该代理不可用地址为{}{}",ip,port);
            return taskNum+"false";
        }
    }
### 如何在Java多线程传递参数Java中实现多线程编程时,可以通过多种方式向新创建的线程传递参数。以下是几种常见的方式: #### 使用构造函数传递参数 通过定义一个实现了`Runnable`接口或继承自`Thread`类的新类,在该类中添加接收外部输入数据的成员变量以及相应的构造方法来初始化这些字段。 ```java class ParameterizedTask implements Runnable { private final String message; // 构造器用于设置任务所需的参数 public ParameterizedTask(String msg) { this.message = msg; } @Override public void run() { System.out.println(Thread.currentThread().getName() + ": " + message); } } ``` 可以这样启动带有参数的任务实例: ```java new Thread(new ParameterizedTask("Hello")).start(); new Thread(new ParameterizedTask("World!")).start(); ``` 这种方法简单明了,并且允许传入多个类型的参数[^1]。 #### 利用匿名内部类即时指定参数 如果只需要临时性的创建并执行一次特定配置下的线程,则可以直接利用匿名内部类的形式来进行快速编码。 ```java String paramValue = "Anonymous Inner Class Example"; Thread t = new Thread(() -> { System.out.println(paramValue); // 访问局部final/有效final变量 }); t.start(); ``` 注意这里访问的是局部最终(`final`)或者实际上不会改变的有效最终变量[^2]。 #### 借助Callable和Future机制返回结果的同时携带额外信息 对于那些不仅希望给定初始状态而且还需要从子进程中获取计算成果的情况来说,应该考虑采用`Callable<V>`接口代替传统的`Runnable`。它支持泛型表示可能产生的输出值类型V,并可通过`ExecutorService.submit()`提交得到对应的`Future<V>`对象以便稍后提取实际运算后的反馈。 ```java 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 class CallableExample { static class TaskWithResult implements Callable<String> { private final int number; public TaskWithResult(int num) { this.number = num; } @Override public String call() throws Exception { return "Result of task with input=" + number; } } public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new TaskWithResult(42)); while (!future.isDone()) {} try { String result = future.get(); // 阻塞直到完成 System.out.println(result); } finally { executor.shutdown(); } } } ``` 上述例子展示了如何安全有效地在线程间共享资源及通信[^3]。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值