【发布时间】:2012-09-05 14:48:47
【问题描述】:
我有 A 类,其中我定义了两个方法 ValidateA 和 ValidateB
class A {
ValidateA() {
/////
}
ValidateB() {
////
}
}
我想同时并行运行这两个步骤并获得组合状态。如何继续使用线程?
【问题讨论】:
标签: java multithreading
我有 A 类,其中我定义了两个方法 ValidateA 和 ValidateB
class A {
ValidateA() {
/////
}
ValidateB() {
////
}
}
我想同时并行运行这两个步骤并获得组合状态。如何继续使用线程?
【问题讨论】:
标签: java multithreading
始终建议使用 Java 5 中引入的出色的 Executors 类。它们可以帮助您管理后台任务并从您的类中隐藏 Thread 代码。
类似下面的东西会起作用。它创建一个线程池,提交 2 个Runnable 类,每个类调用一个验证方法,然后等待它们完成并返回。它使用了一个Result 对象,您必须自己弥补。它也可以是String 或Integer,具体取决于验证方法返回的内容。
// 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();
// ...
}
【讨论】:
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
}
}
【讨论】:
A#startHere() 中调用Object#wait() 是怎么回事?如果调用者没有意识到他需要调用ValidateA() 和ValidateB() 之前调用诱人命名的startHere(),这种设计是强制NullPointerException 的诱饵。