Introduction
Before knowing about the difference between lock frameworks and thread synchronization, we have to know about these things.
Lock framework works like synchronized blocks in Java. It is available in Java.util.concurrent package.
Thread synchronization means that every access to data shared between threads is protected so that when any thread starts operation on the shared data, no other thread is allowed access until the first thread is done.
You can also read about the Multiple Inheritance in Java.
Lock framework
The lock framework works like synchronized blocks in Java, except locks can be more sophisticated than synchronized blocks of Java. The lock framework is available in the Java.util.concurrent package. Java locks act as a thread synchronization mechanism similar to synchronized blocks. This mechanism was introduced in Java 5 and provided more options than the Synchronized block.
Read More About, Basics of Java
Example
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class DisplayDemo
{
private final Lock QueueLock = new ReentrantLock();
public void display()
{
QueueLock.lock();
try
{
Long time=(long) (Math.random()*4000);
System.out.println(Thread.currentThread().getName()+" Time stack "+(time/1000)+" seconds.");
Thread.sleep(time);
}
catch(InterruptedException exp)
{
exp.printStackTrace();
}
finally
{
System.out.printf("%s displayed the document successfully.\n", Thread.currentThread().getName());
QueueLock.unlock();
}
}
}
class ThreadDemo extends Thread
{
DisplayDemo displayDemo;
ThreadDemo(String str_name, DisplayDemo displayDemo)
{
super(str_name);
this.displayDemo=displayDemo;
}
@Override
public void run()
{
System.out.printf("%s starts displaying a document\n", Thread.currentThread().getName());
displayDemo.display();
}
}
public class Example_Lock
{
public static void main (String[] args) throws java.lang.Exception
{
DisplayDemo DD= new DisplayDemo();
ThreadDemo th1 = new ThreadDemo("Thread-1 ", DD);
ThreadDemo th2 = new ThreadDemo("Thread-2 ", DD);
ThreadDemo th3 = new ThreadDemo("Thread-3 ", DD);
ThreadDemo th4 = new ThreadDemo("Thread-4 ", DD);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
Output
Thread-1 starts displaying a document
Thread-1 Time stack 3 seconds.
Thread-2 starts displaying a document
Thread-3 starts displaying a document
Thread-4 starts displaying a document
Thread-1 displayed the document successfully.
Thread-2 Time stack 1 seconds.
Thread-2 displayed the document successfully.
Thread-3 Time stack 3 seconds.
Thread-3 displayed the document successfully.
Thread-4 Time stack 1 seconds.
Thread-4 displayed the document successfully.
The above program demonstrates some methods of the Lock interface. Here we have used lock() to acquire the lock and unlock() to release the lock. We have used ReentrantLock class as an implementation of the Lock interface.
Try it on java online compiler.
Must Read Static Blocks In Java.