Handling if thread could not enter synchronized(this) block

83 Views Asked by At

I am working on a Robotic Analog to digital button listener.

Where There is a synchronized (this) block when the action performed.

public void Init() {   
 new Timer(200, taskPerformer).start();
)

ActionListener taskPerformer = new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    //not synchronized code

        synchronized (this) {
               //synchronized code
        }  

    }
}

Now my question is How can I understand which Thread Failed to enter that block? Is there any way so that I can handle those threads. Similar to the if-else , can I handle those thread who could not entered.

Edit: simply want to print("Could not Enter The Block"); How can I do that.?

Thanks.

1

There are 1 best solutions below

5
On

you can lock on an Object (instead of this) which is shared across group of Threads where you need real synchronization

lock object

Object lockGroup1 = new Object();

Thread that holds it

class MyThread implements Runnable {
  Object lock;
  public MyThread(Object lock){
     this.lock = lock;
  }
  // other stuff ofcourse
}

and

MyThread thread1 = new MyThread(lock1);

Updates based on Comments

    Set<Long> waitingThreads = Collections.synchronizedSet(new HashSet<Long>());
    public void myMethod() {
     waitingThreads.add(Thread.currentThread().getId());
     synchronized (this){
        waitingThreads.remove(Thread.currentThread().getId());

      }
    }