问题
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:
- Create a wrapper class around your unsafe file-updater-class.
- 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)
- Let the other threads call your wrapper class instead.
来源:https://stackoverflow.com/questions/27478888/java-thread-communication-independent-file-reading-and-wiriting