【问题标题】:Why my cyclicBarrier is null?为什么我的 cyclicBarrier 为空?
【发布时间】:2016-09-04 00:51:21
【问题描述】:

我正在学习 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。在那之后,你创建了我所有的线程设置一个任务(设置循环障碍。任务实现可运行)。我的任务代码如下:

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)

调试我可以看到,我的任务中的 cyclicbarrier(barrier) 始终为空,但 cb 不是。

可能是什么问题?

【问题讨论】:

    标签: java multithreading concurrency java.util.concurrent cyclicbarrier


    【解决方案1】:

    因为您在FileDownloader 构造函数中创建了一个本地cb 变量,但您将未初始化的this.cb 传递给Task 构造函数。

    【讨论】:

      【解决方案2】:

      仔细查看您的代码。

      你创建局部变量 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
      

      要专心。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-26
        • 2010-11-25
        • 2018-04-07
        • 2015-02-22
        • 2017-12-07
        • 2010-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多