如何在回调方法中启动单独的线程返回一个值?

时间:2013-12-11 00:55:35

标签: java android multithreading concurrency return-value

我想把这个回调方法中的代码放到一个单独的线程中,以防止缓慢阻止此代码的处理时间以提高执行速度,但是当它尝试这个时它给了我一个编译器的错误该方法没有回报。

看起来编译器希望返回在我开始的新线程之外。

如何使return方法中的代码作为单独的执行过程运行?

 public Mat onCameraFrame(final CvCameraViewFrame inputFrame) {

 new Thread(){
   public void run() {

   mRgba = inputFrame.rgba();
   mGray = inputFrame.gray();

   MatOfRect circles = new MatOfRect();

      Imgproc.GaussianBlur(mGray, mGray, new Size(5, 5), 2, 2);  

     Imgproc.HoughCircles( mGray, circles, Imgproc.CV_HOUGH_GRADIENT,
     1, mGray.rows()/8, 150, 50, 0, 0 );

 if (circles.cols() > 0)
 for (int x = 0; x < circles.cols(); x++) 
 {
 double vCircle[] = circles.get(0,x);

 if (vCircle == null)
 break;

 Point pt = new Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
     int radius = (int)Math.round(vCircle[2]);

 // draw the found circle
 Core.circle(mRgba, pt, radius, new Scalar(0,255,0), 7);
 Core.circle(mRgba, pt, 3, new Scalar(0,0,255), 7);
 }

 return mRgba; // <-- complier wants this to be outside of this thread

 } // end run
 }.start();

 } // oncameraframe

1 个答案:

答案 0 :(得分:0)

Runnable interface无法返回值。使用Callable interface

执行者的例子:

ExecutorService executor = Executors.newCachedThreadPool();
Future<Integer> f = executor.submit(new Callable<Integer>()
{
    public Integer call()
    {
        return 2;
    }
});

对象f将保存您的结果。

在您的示例中,mRgba是字段,因此可以稍后访问。您可以使用同步它,而不必返回结果。结果可以保存在此变量中。