我學習了關於ciclycbarrier,並試圖創建一個小應用程序。我的應用程序的構造是如下:爲什麼我的cyclicBarrier爲空?
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。之後,y創建我的所有線程設置任務(設置cyclicbarrier。任務實現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(我的任務內運行)結束,它的時間做cb.await,我有一個錯誤:
Exception in thread "Hilo1" java.lang.NullPointerException
at Prac2.Task.run(FileDownloader.java:23)
at java.lang.Thread.run(Thread.java:745)
和調試我可以看到在我的任務中的cyclicbarrier(障礙)總是空的,但cb沒有。
你是對的!謝謝!! –