自己写的一个例子,其实jdk 中的ReentrantReadWriteLock这个类已经实现了你说的全部功能了。 以下是多线程读写操作文件的一个例子,如果你觉得线程太多调试麻烦,可以将线程数改小一点就可以了。 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;public class ReadWriteFileThread { private static final int READ_WIRTE_LOOP_COUNT = 10; private static final ReentrantReadWriteLock locker = new ReentrantReadWriteLock( false); private static final WriteLock writeLocker = locker.writeLock(); private static final ReadLock readLock = locker.readLock(); private static final AtomicInteger threadIndex = new AtomicInteger(1); private static final int READ_THREAD_NUMBER = 5; private static final int WRITE_THREAD_NUMBER = 5; private static final List<Thread> readThreads = new ArrayList<Thread>( READ_THREAD_NUMBER); private static final List<Thread> writeThreads = new ArrayList<Thread>( WRITE_THREAD_NUMBER); /** the specified file **/ private static final File f = new File("c:\\aa.txt"); /** the read runnable worker **/ private static final Runnable r = new ReadRunnable(f); /** the write runnable worker **/ private static final Runnable w = new WriteRunnable(f); /** * ThreadFactory is used for create the specified thread */ private static final ThreadFactory tf = new ThreadFactory() { /** * create new thread instance */ public Thread newThread(Runnable r) { final Thread t = new Thread(r); if (r instanceof ReadRunnable) { t.setName("readThread" + threadIndex.getAndIncrement()); readThreads.add(t); } else if (r instanceof WriteRunnable) { t.setName("writeThread" + threadIndex.getAndIncrement()); writeThreads.add(t); } else { throw new RuntimeException("the Runnable is not support.."); } t.setDaemon(false); return t; } }; public static void main(String[] args) { // create read thread for (int i = 0; i < READ_THREAD_NUMBER; i++) { tf.newThread(r); } // create write thread for (int i = 0; i < WRITE_THREAD_NUMBER; i++) { tf.newThread(w); } // start the following threads for (final Thread t : readThreads) { t.start(); } for (final Thread t : writeThreads) { t.start(); } } /** * ReadRunnable for read from file <br> * once a read thread is reached, the other read can be access * successfully..<br> * but the write thread will be blocked until all read thread is done <br> * * @see {@link ReentrantReadWriteLock } * @see {@link ReadLock} * * @author Administrator * */ static class ReadRunnable implements Runnable { private final File file; public ReadRunnable(final File file) { this.file = file; } public void run() { final Thread t = Thread.currentThread(); int loop = 0; while (loop++ < READ_WIRTE_LOOP_COUNT) { try { readLock.lock(); System.out.println("ready to read from file, thread name:" + t.getName()); BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException ex) { System.out.println("the file has not been created yet. " + "need to wait for write thread"); } catch (IOException ex) { ex.printStackTrace(); } finally { readLock.unlock(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * WriteRunnable for write to file <br> * once a write thread is reached, the other write can not be access <br> * and the read thread also been blocked until the write thread is done <br> * * @see {@link ReentrantReadWriteLock } * @see {@link WriteLock} * * @author Administrator * */ static class WriteRunnable implements Runnable { private final File file; public WriteRunnable(final File file) { this.file = file; } public void run() { final Thread t = Thread.currentThread(); int loop = 0; while (loop++ < READ_WIRTE_LOOP_COUNT) { try { writeLocker.lock(); System.out.println("ready to write to file, thread name:" + t.getName()); BufferedWriter br = new BufferedWriter(new FileWriter(file, true)); br.write("hello world! wirte thread Name:" + t.getName() + "\r\n"); br.flush(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { writeLocker.unlock(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
以下是多线程读写操作文件的一个例子,如果你觉得线程太多调试麻烦,可以将线程数改小一点就可以了。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;public class ReadWriteFileThread {
private static final int READ_WIRTE_LOOP_COUNT = 10; private static final ReentrantReadWriteLock locker = new ReentrantReadWriteLock(
false);
private static final WriteLock writeLocker = locker.writeLock();
private static final ReadLock readLock = locker.readLock();
private static final AtomicInteger threadIndex = new AtomicInteger(1); private static final int READ_THREAD_NUMBER = 5;
private static final int WRITE_THREAD_NUMBER = 5; private static final List<Thread> readThreads = new ArrayList<Thread>(
READ_THREAD_NUMBER);
private static final List<Thread> writeThreads = new ArrayList<Thread>(
WRITE_THREAD_NUMBER); /** the specified file **/
private static final File f = new File("c:\\aa.txt"); /** the read runnable worker **/
private static final Runnable r = new ReadRunnable(f); /** the write runnable worker **/
private static final Runnable w = new WriteRunnable(f); /**
* ThreadFactory is used for create the specified thread
*/
private static final ThreadFactory tf = new ThreadFactory() {
/**
* create new thread instance
*/
public Thread newThread(Runnable r) {
final Thread t = new Thread(r); if (r instanceof ReadRunnable) {
t.setName("readThread" + threadIndex.getAndIncrement());
readThreads.add(t);
} else if (r instanceof WriteRunnable) {
t.setName("writeThread" + threadIndex.getAndIncrement());
writeThreads.add(t);
} else {
throw new RuntimeException("the Runnable is not support..");
}
t.setDaemon(false);
return t;
}
}; public static void main(String[] args) {
// create read thread
for (int i = 0; i < READ_THREAD_NUMBER; i++) {
tf.newThread(r);
} // create write thread
for (int i = 0; i < WRITE_THREAD_NUMBER; i++) {
tf.newThread(w);
} // start the following threads
for (final Thread t : readThreads) {
t.start();
} for (final Thread t : writeThreads) {
t.start();
} } /**
* ReadRunnable for read from file <br>
* once a read thread is reached, the other read can be access
* successfully..<br>
* but the write thread will be blocked until all read thread is done <br>
*
* @see {@link ReentrantReadWriteLock }
* @see {@link ReadLock}
*
* @author Administrator
*
*/
static class ReadRunnable implements Runnable {
private final File file; public ReadRunnable(final File file) {
this.file = file;
} public void run() {
final Thread t = Thread.currentThread();
int loop = 0;
while (loop++ < READ_WIRTE_LOOP_COUNT) {
try {
readLock.lock();
System.out.println("ready to read from file, thread name:"
+ t.getName());
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException ex) {
System.out.println("the file has not been created yet. "
+ "need to wait for write thread");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
readLock.unlock();
} try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} /**
* WriteRunnable for write to file <br>
* once a write thread is reached, the other write can not be access <br>
* and the read thread also been blocked until the write thread is done <br>
*
* @see {@link ReentrantReadWriteLock }
* @see {@link WriteLock}
*
* @author Administrator
*
*/
static class WriteRunnable implements Runnable {
private final File file; public WriteRunnable(final File file) {
this.file = file;
} public void run() {
final Thread t = Thread.currentThread();
int loop = 0;
while (loop++ < READ_WIRTE_LOOP_COUNT) {
try {
writeLocker.lock();
System.out.println("ready to write to file, thread name:"
+ t.getName());
BufferedWriter br = new BufferedWriter(new FileWriter(file,
true));
br.write("hello world! wirte thread Name:" + t.getName()
+ "\r\n");
br.flush();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
writeLocker.unlock();
} try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}