Part 6: java.util.concurrent - Lock and Condition Object
Today in next part of the series we will talk about How to communicate among threads using Lock and Condition Objects.
In traditional Java - If we need to communicate among threads, we syncronize code and use "wait" and "notify" methods of Object class.
From Java 5.0 and above - Lock inte易做图ce provides an easier implmentation for synchronization and Condition class can be used to wait and notify threads.
Lock has several important methods such as "lock", "tryLock", "lockInterruptibly" etc, whereas Condition has "await", "signal", 'signalAll" etc. In this article we will demonstrate the usage of 3 methods - "lock" (from Lock inte易做图ce), "await", "signal" (from Condition Class).
Lets try to visualize a scenario here - Assume we have 2 process "Reader" and "Writer". Writer writes on a file and Reader reads from a file. we want to add a listener to writer object so that whenever writer writes anything on a file, "Reader" will be called and it will read the same data. Before we look into codes lets look at the some important points to use Lock and Condition-
1) Lock is an Inte易做图ce, the most common implementation class is ReentrantLock. Others two are - ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
2) Condition Object is always retrieved from Lock object. For example - Condition condition = lock.newCondition( );
3) One of the best practice to use Lock is-
Lock lockObj = new ReentrantLock( );
lockObj.lock( );
try{
.... code..
}finally{
lockObj.unlock( );
}
4) condition.await, condition.signal, condition.signalAll methods should only be called once you have acquired the lock by - lockObj.lock( ).
In our example, the design of the class will be something like this -
> One lock Object == fileLock
> One condition Object = condition = fileLock.newCondition
Pseudo code for Writer Thread
// GET the LOCK
try{
// -- In the Loop untill EXIT---
//Write on the file
// Signal the READER
//If EXIT signal then exit else "WAIT for READER to SIGNAL"
}finally{
// RELEASE the LOCK
}
pseudo code for Reader Thread
// GET the LOCK
try{
// -- In the Loop untill EXIT---
//Read from the file
// Signal the WRITER
// If EXIT signal - then exit else "WAIT for WRITER to SIGNAL"
}finally{
// RELEASE the LOCK
}
package com.jovialjava.blog.threads;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private static final String fileName = "LockExample.txt";
private static final String EXIT_FLAG = "BYE";
private static final int NO_OF_LINES = 10;
private static final Lock fileLock = new ReentrantLock();
private static final Condition condition = fileLock.newCondition();
private static final ExecutorService executorPool = Executors.newFixedThreadPool(2);
public static void main(String args) {
Runnable fileWriter = new FileWrite();
Runnable fileReader = new FileRead();
executorPool.submit(fileReader);
executorPool.submit(fileWriter);
executorPool.shutdown();
}
/**
* This thread will write on a file and inform the reader thread to read it.
* If it has not written the EXIT flag then it will go into wait stage and
* will wait for READER to signal that it safe to write now.
*/
public static class FileWrite implements Runnable {
public void run() {
try {
fileLock.lock();
for (int i = 0; i < NO_OF_LINES; i++) {
PrintWriter writer = new PrintWriter(new File(fileName));
if (i != NO_OF_LINES - 1) {
int random = new SecureRandom().nextInt();
System.out.println("WRITER WRITING " + random);
writer.println(random);
writer.close();
// signallng to READER that its safe to read now.
condition.signal();
System.out.println("Writer waiting");
condition.await();
} else {
&n
补充:软件开发 , Java ,