Is there any way to run a piece of code when a thread accesses a locked object ?
public class Student implements Runnable {
private String name;
private Workshop w;
public Student(String name,Workshop workshop) {
this.name = name;
this.w=workshop;
}
@Override
public void run() {
this.w.getReady();
this.w.file(this.name);
this.w.cut(this.name);
this.w.punch(this.name); //Synchronized Method
if(Thread.currentThread().getState()==Thread.State.BLOCKED)
System.out.println(this.name+" is waiting in queue");
System.out.println(this.name+" has finished and is going home");
}
}
This is a simulation for a Workshop scenario where each and every student has to file,cut and punch the metal workpiece.
Since punching is turn by turn, I have declared it as synchronized, as every student (thread) will have to wait for their turn to punch.
All I want to know is,if there some in-built method or a way to write a method that gets executed when a thread gets blocked and is waiting for the intrinsic lock to be unlocked.
Example
public void onBlock() {
System.out.println(this.name+" is waiting in queue");
...
}
For object monitors protected by synchronized
, no, it either successfully locks or it blocks indefinitely waiting for a lock.
If you're using a ReentrantLock
or the like, you have more options:
lock
.tryLock
with a timeout value.tryLock
with no arguments.