java线程通信,独立的文件读取和写入 [英] java thread communication, independent file reading and wiriting

查看:53
本文介绍了java线程通信,独立的文件读取和写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java.我有两个线程.一个将持续监视某些事件,并基于这些事件将更新(添加或删除)文件.另一个线程是计时器任务事件,它将定期更新同一文件.我希望其他线程不访问文件时这些线程更新文件.我无法使用锁,因为文件更新代码部分对于每个线程和不同的Java类而言都是独立的.我该怎么办?预先感谢.

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.

推荐答案

您可以使用同步.

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.

这篇关于java线程通信,独立的文件读取和写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆