-2

我學習了關於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沒有。

可能是什麼問題? enter image description here

回答

1

仔細查看你的代碼。

您創建本地變量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 

要細心。

+0

你是對的!謝謝!! –

2

因爲你創建的FileDownloader構造一個局部變量cb,但你傳遞未初始化的this.cbTask構造。