簡體   English   中英

同步塊內部運行方法

[英]Synchronized Block inside run method

如果我有類似下面的內容,那么在synchronized block內是什么意思

synchronised (syncObject) {

基本上,這意味着只有一個線程可以在上述塊內,並且一旦一個線程執行完畢,第二個線程將進入該同步塊synced(syncObject) 對? 誰能用LayMan語言向我解釋,以便獲得更好的照片?

private static final class Task implements Runnable {
{
  private static Object syncObject = new Object();

    public Task(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
    this.command = command;
    this.existPool = pool1;
    this.newPool = pool2;
}

  public void run()
  {
    synchronised (syncObject) {
      if() {
        existId = existPool.take();
        attributeMethod(existId);
        } else if() {
            newId = newPool.take();
            attributeMethod(newId);
        }
    }
  }
}

// So I need to make this method synchronized or not? Currently I have made this synchronized
private synchronized void attributeMethod(int range) {
    // And suppose If I am calling any other method here-

 sampleMethod();
}


// What about this method, I need to make this synchronized as well? or not?
private synchronized void sampleMethod() {


}

基本上,這意味着只有一個線程可以在上述塊內,並且一旦一個線程執行完,第二個線程將進入已同步塊(syncObject)。 對?

對!

所以我需要使這種方法同步或不同步?

不,你不會。 假設只從run()方法中的同步塊中調用該方法,則該塊將已經防止多個線程同時執行該方法。 因此,聲明要synchronized的方法是多余的。

但是,我應該指出一些事情:

  • 當您將實例方法聲明為已synchronized ,它將在this方法上進行synchronized 即在Task對象上。 但是您的synchronized塊正在另一個對象上同步... syncObject對象中的對象。 在這種情況下,這無關緊要。 但是,如果不存在run()方法中的synchronized塊,則您會發現線程正在嘗試在不同的對象上進行同步...並且您不會相互排斥。

  • 通過在run()方法的頂層進行同步...對執行該任務的所有線程使用單個共享的syncObject ...您可以有效地使這些任務一次運行。 這完全否定了使用線程的任何好處。

  • 優良作法是將包含私有鎖定對象(例如syncObject )的變量聲明為final 這避免了某些東西可能覆蓋它的可能性,從而導致同步失敗。

否, attributeMethod已在synchronized塊范圍內運行; 除非您打算在此塊之外同時調用它,否則無需將其標記為此類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM