gpt4 book ai didi

java - Java中的多线程最佳实践

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:18 25 4
gpt4 key购买 nike

我是 Java 编程的新手。我有一个用例,我必须并行执行 2 个数据库查询。我类(class)的结构是这样的:

class A {
public Object func_1() {
//executes db query1
}

public Object func_2() {
//executes db query1
}
}

现在我在同一个类中添加了另一个函数 func_3,它调用这 2 个函数,但也确保它们并行执行。为此,我正在使用可调用对象和 future 。以这种方式使用它是正确的方法吗?我将 this 变量存储在一个临时变量中,然后使用它从 func_3 调用 func_1 和 func_2(我不确定这是正确的方法)。或者还有其他方法可以处理此类情况吗?

class A {
public Object func_1() {
//executes db query1
}

public Object func_2() {
//executes db query1
}

public void func_3() {
final A that = this;
Callable call1 = new Callable() {
@Override
public Object call() {
return that.func_1();
}
}

Callable call2 = new Callable() {
@Override
public Object call() {
return that.func_2();
}
}
ArrayList<Callable<Object>> list = new ArrayList<Callable<Object>>();
list.add(call1);
list.add(call2);
ExecutorService executor = Executors.newFixedThreadPool(2);
ArrayList<Future<Object>> futureList = new ArrayList<Future<Object>>();
futureList = (ArrayList<Future<Object>>) executor.invokeAll(list);
//process result accordingly
}
}

最佳答案

首先,您不需要将其存储在另一个局部变量中:外部函数将像 func_1()func_2() 一样可用,并且当您想要获取外部类的 this 只需使用 A.this

其次,是的,这是常见的做法。此外,如果您打算经常调用 func_3 - 避免创建固定线程池,您应该将其作为参数传递,因为线程创建相当“昂贵”。

关于java - Java中的多线程最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com