Click here to Skip to main content
15,921,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
When one thread acquire Interruptibly lock on one method and goes for sleep , And another thread run and try to lock the same method it should throw exception but i am not getting any exception.

import java.util.concurrent.locks.ReentrantLock;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Java program to show, how to use ReentrantLock in Java.
* Reentrant lock is an alternative way of locking
* apart from implicit locking provided by synchronized keyword in Java.
*
* @author Javin Paul
*/
public class ReentrantLockHowto implements Runnable {

public void run(){
ReadFile();
}

private final ReentrantLock lock = new ReentrantLock();

public void ReadFile() {

try {
lock.lockInterruptibly();
String line = "";
FileReader fileReader = new FileReader("D:\\TestFile1.txt");
BufferedReader reader = new BufferedReader(fileReader);
while ((line = reader.readLine()) != null) {
System.out.println("Thread read " + Thread.currentThread().getName() + " : "+ line);
Thread.sleep(10000);
}
System.out.println(Thread.currentThread().getName() + " : file read successfuly");
} catch (Exception e) {
System.out.println("Read" + e.getMessage());
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " : finaly file read successfuly");
}
}


public static void main(String args[]) {
try{
ReentrantLockHowto counter = new ReentrantLockHowto();
Thread t1 = new Thread(counter);
Thread t2 = new Thread(counter);
t1.start();
t2.start();
}
catch (Exception e)
{
System.out.println("Main Exception " + e.getMessage());
}

}
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900