簡體   English   中英

Java靜態變量同步方法

[英]Java Synchronized Method on Static Variable

我正在上一門關於Java並發的大學課程,最近得到了一個簡單的任務,創建5個線程,編號從1到5,然后讓每個線程使用同步的靜態方法將其線程號寫入類中的靜態變量。

講師給我的解決方案如下:

public class thread1 extends Thread {

private int threadNumber;
private static int threadCount = 0;
private static int value;

public thread1(){
      threadNumber = ++threadCount;
      System.out.println("Thread " + threadNumber + " is created" );
}

public synchronized static void setValue(int v){
      value = v;
      try{
           Thread.currentThread().sleep(100);
      }
           catch(InterruptedException e ){}

      System.out.println("the current value of the variable is " + value);
}

public void run() {
    setValue(threadNumber);
    return;
}

public static void main(String[] args) {
    for(int i = 0; i < 5; i++){
        thread1 thr = new thread1();
        thr.start();
}

}
}   

輸出應如下所示:

創建線程1
創建線程2
創建線程3
創建線程4
創建線程5
變量的當前值為1
變量的當前值為2
變量的當前值為3
變量的當前值為4
變量的當前值為5

但是我得到的輸出如下:

創建線程1
創建線程2
創建線程3
創建線程4
創建線程5
變量的當前值為1
變量的當前值為5
變量的當前值為4
變量的當前值為3
變量的當前值為2

當前值的順序每次都明顯不同。

我得到的解決方案不正確嗎? 很顯然,它無法實現其預期的目的,即按順序打印出每個線程的變量。

有人能闡明我如何可靠地每次以1到5的順序打印線程號嗎? 我認為使用同步的setValue方法可以解決問題,但顯然不能。

您的講師提供的解決方案絕對正確。

您沒有得到預期的順序,因為創建了5個不同的線程,並且每個線程都必須訪問相同的同步方法。

當方法同步時,一次只能訪問一個對象

在您的情況下,只有一個線程可以訪問setValue方法

when one Thread enters the method it acquires the lock and 
the other threads wait for the lock ,when this Thread releases the lock , 
any waiting Thread can acquire it and execute the setValue method.

永遠無法保證Threads將以哪種順序執行方法

因此,每次運行該程序時,您將獲得一些不同順序的線程

無法保證線程將按照您對它們調用start方法的順序執行。 同步塊僅意味着兩個線程不能同時訪問它。 線程的運行順序由調度程序確定。

沒有定義線程進入監視器的順序。 一旦線程在監視器內完成執行,則在該監視器上等待的任何其他線程都可以控制關​​鍵部分。

暫無
暫無

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

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