简体   繁体   English

处理线程是否无法进入同步(此)块

[英]Handling if thread could not enter synchronized(this) block

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. 类似于if-else,我可以处理无法输入的那些线程。

Edit: simply want to print("Could not Enter The Block"); 编辑:只是想打印(“无法进入块”); How can I do that.? 我怎样才能做到这一点。?

Thanks. 谢谢。

you can lock on an Object (instead of this ) which is shared across group of Threads where you need real synchronization 您可以锁定一个需要真正同步的线程组之间共享的Object (而不是this

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());

      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM