当线程访问锁定对象时,有什么办法可以运行一段代码吗?当线程被内部锁定阻塞时执行代码
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");
}
}
这是一个模拟车间的场景,每个学生都必须对金属工件进行归档,切割和打孔。
由于冲压轮流转,我已经宣布它是同步的,因为每个学生(线程)将不得不等待轮到他们冲。
所有我想知道的是,如果有一些内置的方法或一种方法来编写一个方法,当一个线程被阻塞并且正在等待内部锁被解锁时被执行。
例
public void onBlock() {
System.out.println(this.name+" is waiting in queue");
...
}
据我所知,不 - 如果你的线程在等待某件事情,它不能停止并执行其他事情(没有一些*真正讨厌的解决方法)。我不完全确定,但是,所以不回答... – awksp