【发布时间】:2017-12-13 21:05:29
【问题描述】:
抱歉,我提出了与在单独线程中运行计算相关的“初学者”问题,但我是一名 C++ 程序员。
处理大图像是一项计算量大的任务。在处理过程中,我希望能够使用我的软件(包括缩放操作)。
基于您的advice(程序返回数据 - 新图像) Callable 接口已被使用:
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<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 接口重写代码
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 接口?如果需要,如何调整?
【问题讨论】:
标签: java multithreading multitasking callable