簡體   English   中英

處理線程是否無法進入同步(此)塊

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

我正在研究一種機器人模擬到數字按鈕監聽器。

在執行操作時,有一個同步的(此)塊。

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

ActionListener taskPerformer = new ActionListener() {

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

        synchronized (this) {
               //synchronized code
        }  

    }
}

現在,我的問題是如何理解哪個線程無法進入該塊? 有什么辦法可以讓我處理那些線程。 類似於if-else,我可以處理無法輸入的那些線程。

編輯:只是想打印(“無法進入塊”); 我怎樣才能做到這一點。?

謝謝。

您可以鎖定一個需要真正同步的線程組之間共享的Object (而不是this

鎖定對象

Object lockGroup1 = new Object();

持有它的線程

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

MyThread thread1 = new MyThread(lock1);

根據評論更新

    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