gpt4 book ai didi

java - 可在单独的线程中调用与可运行和多任务处理

转载 作者:行者123 更新时间:2023-12-01 17:55:46 25 4
gpt4 key购买 nike

很抱歉我的问题有点“初学者”,涉及在单独的线程中运行计算,但我是一名 C++ 程序员。

处理大图像的计算量很大。在处理过程中,我希望能够使用我的软件(包括缩放操作)。

基于您的advice (该过程返回数据 - 一个新图像)Callable接口(interface)已被使用:

public class B implements Callable<BufferedImage> {
private boolean c;

public B (boolean c) { this.c = c; }

public BufferedImage call() {
//Some operations
if (!c)
return null;
return new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
}
}

最初,执行程序服务被创建:

ExecutorService exe = Executors.newFixedThreadPool(2); 
B b = new B(true);

随后,返回 future:

Future<BufferedImage> res = exe.submit(b);

最后,我们等待数据:

BufferedImage img = res.get(); 

不幸的是,这个实现的行为并不符合我的预期。尽管它在单独的线程中工作,但“响应”不会返回到主窗口,并且我无法在计算期间正确使用该软件。

因此,我尝试修改 get() 方法,以便

try
{
BufferedImage img_proj = results.get(5, TimeUnit.MILLISECONDS);
}

catch (Exception e)
{
results.cancel(true);
e.printStackTrace();
}

但是,出现了TimeoutException。使用Runnable接口(interface)重写代码

public class B implements Runnable{
private boolean c;
private Runnable f;

public B (boolean c_, Runnable f_) { c = c_; f = f_;}

public BufferedImage process() {
//Some operations
BufferedImage output = null;
if (c) output = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
return output;
}

public void run() { process();}
}

一起

Thread t = new Thread(b);
t.start ();

并且多任务处理按预期工作......

所以我的问题是:是否有必要另外“调整”或调整 Callable 接口(interface),如果需要,如何调整?

最佳答案

我建议使用你们的执行人服务。

exe.submit(()->{
BufferedImage img = res.get();
uiRelatedMethod(img);
});

这样你的 gui 线程就不会阻塞,并且一旦缓冲的图像可用,它就会收到通知。当然,您必须使用 try/catch block 。

关于java - 可在单独的线程中调用与可运行和多任务处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45006808/

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