java thread communication, independent file reading and wiriting

这一生的挚爱 提交于 2019-12-11 20:12:40

问题


Java. I have two threads. one will be continuously monitoring for some events and based on the events, it will be updating (addition or deletion) a file. the other thread which is a timer task event, will be updating the same file in regular intervals of time. I want the threads to update the file when the other thread is not accessing the file. I couldn't use locks as file updating code part is independent for each thread and in different java classes. how can i do so? thanks in advance.


回答1:


You can use synchronization.

public synchronized void update() {
..
..
..
}

so only one thread access the method. Other will wait on the lock.

If you have add,update,delete method then,

private static Object LOCK = new Object(); 

public void update() {
  synchronized(LOCK) {
    ..
    ..
    ..
    }
}

public void add() {
  synchronized(LOCK) {
    ..
    ..
    ..
    }
}

public void delete() {
  synchronized(LOCK) {
    ..
    ..
    ..
    }
}

So Only one thread can able to edit/delete/add the file.

if one thread is adding , second thread is trying to delete then it will wait first thread to add.




回答2:


synchronized  void updateFILE
{
       //Your operation here
}

So at a time one thread can perform opetation.. You can have look at here




回答3:


Perhaps you could:

  1. Create a wrapper class around your unsafe file-updater-class.
  2. Make that wrapper class thread-safe by adding your synchronization or locks that clearly defines the critical sections and handle all exceptions appropriately (for example, unlock the critical section in a finally-block)
  3. Let the other threads call your wrapper class instead.


来源:https://stackoverflow.com/questions/27478888/java-thread-communication-independent-file-reading-and-wiriting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!