-4

我有 A 类,其中我有两个方法定义 ValidateA 和 ValidateB

class A {
   ValidateA() {
        /////
    }

   ValidateB() {
        ////
    }
}

我想同时并行运行这两个步骤并获得组合状态。我怎样才能继续使用线程?

4

2 回答 2

4

始终建议使用ExecutorsJava 5 中引入的出色类。它们可以帮助您管理后台任务并隐藏Thread类中的代码。

像下面这样的东西会起作用。它创建一个线程池,提交 2 个Runnable类,每个类调用一个 validate 方法,然后等待它们完成并返回。它使用Result你必须弥补的对象。它也可以是StringorInteger并且取决于 validate 方法返回的内容。

// reate an open-ended thread pool
ExecutorService threadPool = Executors.newCachedThreadPool();
// since you want results from the validate methods, we need a list of Futures
Future<Result> futures = new ArrayList<Result>();
futures.add(threadPool.submit(new Callable<Result>() {
    public Result call() {
       return a.ValidateA();
    } 
});
futures.add(threadPool.submit(new Callable<Result>() {
    public Result call() {
       return a.ValidateB();
    } 
});
// once we have submitted all jobs to the thread pool, it should be shutdown,
// the already submitted jobs will continue to run
threadPool.shutdown();

// we wait for the jobs to finish so we can get the results
for (Future future : futures) {
    // this can throw an ExecutionException if the validate methods threw
    Result result = future.get();
    // ...
}
于 2012-09-05T15:08:53.443 回答
0

阅读有关CyclicBarrier的信息

class A {
  public Thread t1;
  public Thread t2;
  CyclicBarrier cb = new CyclicBarrier(3);
  public void validateA() {
    t1=new Thread(){
       public void run(){
         cb.await();       //will wait for 2 more things to get to barrier
          //your code
        }};
    t1.start();
  }
  public void validateB() {
    t2=new Thread(){
       public void run(){
         cb.await();      ////will wait for 1 more thing to get to barrier
          //your code
        }};
    t2.start();
  }
  public void startHere(){
        validateA();
        validateB();
        cb.wait();      //third thing to reach the barrier - barrier unlocks-thread are                 running simultaneously
  }
}
于 2012-09-05T15:14:14.783 回答