下面的代码似乎不是并行运行的,而是在另一个请求之后发出一个请求,甚至在每个单独的线程上调用await()方法。有人可以帮助并行进行此线程调用。
public class XYZ {
private static String baseUrl = "http://xyz.polls.com";
public static void main(String[] args) {
MultiThreadedHttpConnectionManager conMgr =new MultiThreadedHttpConnectionManager();
HostConfiguration hostConf = new HostConfiguration();
hostConf.setHost("xyz.polls.com");
HttpConnectionManagerParams connParam = new HttpConnectionManagerParams();
connParam.setMaxConnectionsPerHost(hostConf, 5);
connParam.setMaxTotalConnections(5);
conMgr.setParams(connParam);
HttpClient client = new HttpClient(conMgr);
client.setHostConfiguration(hostConf);
CyclicBarrier cyclicBarrier = new CyclicBarrier(1, new Runnable() {
private int count = 1;
public void run() {
System.out.printf("Cyclic Barrier Finished %d\n", count++);
}
});
System.out.println("Spawning Threads");
for(int i = 0; i < 1; i++){
Thread t1 = new Thread(new UpdateProfile(cyclicBarrier, client));
t1.start();
Thread t2 = new Thread(new UpdateAccount(cyclicBarrier, client));
t2.start();
}
System.out.println("Spawning Finished");
}
private static class UpdateAccountThread implements Runnable{
private CyclicBarrier cyclicBarrier;
private HttpClient httpClient;
public UpdateAccountThread(CyclicBarrier cyclicBarrier, HttpClient httpClient){
this.cyclicBarrier = cyclicBarrier;
this.httpClient = httpClient;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try{
int count = cyclicBarrier.await();
System.out.println("UpdateAccountThread : Cyclic Barrier count on " +count);
updateAccount(httpClient);
}catch (BrokenBarrierException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static class UpdateProfileThread implements Runnable{
private CyclicBarrier cyclicBarrier;
private HttpClient httpClient;
public UpdateProfileThread(CyclicBarrier cyclicBarrier, HttpClient httpClient){
this.cyclicBarrier = cyclicBarrier;
this.httpClient = httpClient;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try{
int count = cyclicBarrier.await();
System.out.println("UpdateProfileThread : Cyclic Barrier count on " +count);
updateProfile(httpClient);
}catch (BrokenBarrierException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void updateProfile(HttpClient client){
// logic here
}
private static void updateAccount(HttpClient client){
// logic here
}
}
最佳答案
您正在使用步骤1初始化CyclicBarrier:
CyclicBarrier cyclicBarrier = new CyclicBarrier(1, new Runnable()....
您应该将其更改为2,以便此屏障等待2个线程到达然后中断。
关于java - CyclicBarrier启动执行不同逻辑的并行线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24130604/