线程永远不允许访问同步的代码块

时间:2016-08-05 19:07:24

标签: java multithreading

Future对象永远无法获得对同步代码块的访问权限,因此它永远不会完成并且永远不会返回。除了线程之外,没有任何东西可以访问writeOut()所以我不确定它为什么会阻塞。

public class FileManager {
   private void writeOut() throws BusinessException {
    if(f.exists() && f.canWrite()) {
        synchronized (this) {
            try (FileWriter fileWriter = new FileWriter(f)) {
                String endLine = "\n";
                fileWriter.write("");
                for (Entry entry : directory) {
                    fileWriter.append(entry.getLastName());
                    fileWriter.append(CSV_DELIMITER);
                    fileWriter.append(entry.getFirstName());
                    fileWriter.append(CSV_DELIMITER);
                    fileWriter.append(entry.getPhoneNumber());
                    fileWriter.append(CSV_DELIMITER);
                    fileWriter.append(entry.getAddress());
                    fileWriter.append(endLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        System.out.println(f.getAbsolutePath() + " doesn't exist or can't be written to");
    }
  }

   public void addEntry(Entry entryModel, boolean notify) {
      assert entryModel != null;
      synchronized (this) {
        AddEntryAction addAction = new AddEntryAction(entryModel, notify);
        AddEntryActor actor = new AddEntryActor(addAction);
        actor.execute();
        deleteActor(actor);
      }
   }

以下是execute()调用的方法:

private void executeAsynchronously() {
    Callable<String> asyncTask = () -> {
        try {
            ServiceFw.fileManager.writeBack();
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BusinessException e) {
            notifyFailure();
        }
        return "write back operation";
    };
    future = executor.submit(asyncTask);
    Runnable poll = () -> {
        if(future!=null) {
            notifySuccess();
        } else {
            notifyFailure();
        }
    };
    poll.run();
}

0 个答案:

没有答案