gpt4 book ai didi

java - CyclicBarrier 启动执行不同逻辑的并行线程

转载 作者:行者123 更新时间:2023-12-02 05:45:21 24 4
gpt4 key购买 nike

下面的代码似乎不是并行运行的,而是在每个单独的线程上调用 wait() 方法的情况下,在另一个请求之后发出一个请求。有人可以帮助并行调用该线程吗?

 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 cycloBarrier = new CyclicBarrier(1, new Runnable()....

您应该将其更改为 2,以便此屏障等待 2 个线程到达然后中断。

关于java - CyclicBarrier 启动执行不同逻辑的并行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com