[英]Why does Java have both CountDownLatch and CyclicBarrier?
[英]Why my cyclicBarrier is null?
我学习了 ciclycbarrier,我正在尝试创建一个小应用程序。 我的应用程序的构造函数如下:
public FileDownloader(String line, int maxDownload){
this.position = 0;
this.line = line;
this.maxDownload = maxDownload;
this.urls = new ArrayList<String>();
this.ths = new ArrayList<Thread>();
this.exm = new Semaphore(1);
this.GenerateURLS();
final CyclicBarrier cb = new CyclicBarrier(this.maxDownload, new Runnable(){
@Override
public void run(){
System.out.println("All download are finished");
//Mergear cuando se termina
//Borrar cuando se termina
}
});
for(int i=0; i<this.maxDownload;i++){
ths.add(new Thread(new Task(this.cb),"Hilo"+i));
}
for(Thread th: ths){
th.start();
}
}
在构造函数中,我创建了我的 Cyclicbarrier,设置了一个 maxDownload 数和一个新的 Runnable。 在那之后,你创建了我所有的线程来设置一个任务(设置循环屏障。任务实现了 Runnable)。 我的任务代码如下:
class Task implements Runnable{
private CyclicBarrier barrier;
public static int position;
public Task(CyclicBarrier cb){
this.barrier = cb;
}
public void run(){
try {
FileDownloader.DownloadManager();
this.barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getStackTrace());
}
}
}
但问题是,当方法 DownloadFile(Inside Run of my task) 结束时,是时候执行 cb.await 了,我遇到了下一个错误:
Exception in thread "Hilo1" java.lang.NullPointerException
at Prac2.Task.run(FileDownloader.java:23)
at java.lang.Thread.run(Thread.java:745)
和调试我可以看到我的任务中的循环障碍(障碍)始终为空,但 cb 不是。
因为您在FileDownloader
构造函数中创建了一个本地cb
变量,但是您将未初始化的this.cb
传递给了Task
构造函数。
仔细查看您的代码。
您创建局部变量 cb。
final CyclicBarrier cb = new CyclicBarrier(this.maxDownload, new Runnable(){
@Override
public void run(){
System.out.println("All download are finished");
//Mergear cuando se termina
//Borrar cuando se termina
}
});
但是在这里您可以访问类级变量。
for(int i=0; i<this.maxDownload;i++){
ths.add(new Thread(new Task(this.cb),"Hilo"+i));
}
我的意思是:
this.cb
留心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.