java.util.concurrent.locks.readwritelock
接口允许一次读取多个线程,但一次只能写入一个线程。
readwritelock
进行写入,则多线程可以访问读锁。以下是lock
类中可用的重要方法的列表。
编号 | 方法 | 描述 |
---|---|---|
1 | public lock readlock() |
返回用于读的锁。 |
2 | public lock writelock() |
返回用于写的锁。 |
以下testthread
程序演示了readwritelock
接口的这些方法。这里我们使用readlock()
获取读锁定和writelock()
来获取写锁定。
import java.util.concurrent.locks.reentrantreadwritelock;
public class testthread {
private static final reentrantreadwritelock lock = new reentrantreadwritelock(true);
private static string message = "a";
public static void main(string[] args) throws interruptedexception{
thread t1 = new thread(new writera());
t1.setname("writer a");
thread t2 = new thread(new writerb());
t2.setname("writer b");
thread t3 = new thread(new reader());
t3.setname("reader");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
static class reader implements runnable {
public void run() {
if(lock.iswritelocked()) {
system.out.println("write lock present.");
}
lock.readlock().lock();
try {
long duration = (long) (math.random() * 10000);
system.out.println(thread.currentthread().getname()
+ " time taken " + (duration / 1000) + " seconds.");
thread.sleep(duration);
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
system.out.println(thread.currentthread().getname() +": "+ message );
lock.readlock().unlock();
}
}
}
static class writera implements runnable {
public void run() {
lock.writelock().lock();
try {
long duration = (long) (math.random() * 10000);
system.out.println(thread.currentthread().getname()
+ " time taken " + (duration / 1000) + " seconds.");
thread.sleep(duration);
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
message = message.concat("a");
lock.writelock().unlock();
}
}
}
static class writerb implements runnable {
public void run() {
lock.writelock().lock();
try {
long duration = (long) (math.random() * 10000);
system.out.println(thread.currentthread().getname()
+ " time taken " + (duration / 1000) + " seconds.");
thread.sleep(duration);
} catch (interruptedexception e) {
e.printstacktrace();
} finally {
message = message.concat("b");
lock.writelock().unlock();
}
}
}
}
这将产生以下结果,如下所示 -
writer a time taken 6 seconds.
write lock present.
writer b time taken 2 seconds.
reader time taken 0 seconds.
reader: aab