簡體   English   中英

Java中的MultiTheading具有靜態和非靜態方法

[英]MultiTheading in Java having static and non static method

我一直在嘗試java中的多線程的不同行為。 如果我在類中使用同步靜態和非靜態方法。 我所理解的是,

- >如果線程進入同步方法,則線程獲取對象的鎖定,直到執行方法。

- >如果線程進入靜態同步方法,則線程獲取類的鎖而不是對象。

Real confusion部分是輸出??。

    package com.threadImplementaion.examples;

class MyRunable implements Runnable
{
    public void run()
    {
        iterationMethod() ;
        staticIteration();
    }
    public synchronized void iterationMethod() 
    {
        //int count = 0  ;
        for(int i = 0 ; i < 5; i++ )
        {
            System.out.println( Thread.currentThread().getName() + " : " +  i);
        }
    }
    public  static synchronized  void staticIteration()
    {
        for(int i = 0 ; i < 10 ; i++ )
        {
            System.out.println(Thread.currentThread().getName() +  " static "  +  i);
        }
    }
}
public class MyRunnable 
{
    public static void main(String[] args) {
        Runnable runnable = new MyRunable() ;
        Thread thread1 = new Thread(runnable);
        thread1.start();
        thread1.setName("Thread1");
        Thread thread2 = new Thread(runnable) ;
        thread2.start();
        thread2.setName("Thread2") ;
        Thread thread3 = new Thread(runnable); 
        thread3.start();
        thread3.setName("Thread3");
        }


}



Output :
Thread1 : 0
Thread1 : 1
Thread1 : 2
Thread1 : 3
Thread1 : 4
Thread1 static 0
Thread1 static 1
Thread1 static 2
Thread1 static 3
Thread1 static 4
Thread1 static 5
**Thread1 static 6**
Thread3 : 0
Thread3 : 1
Thread3 : 2
Thread3 : 3
Thread3 : 4
Thread2 : 0
Thread2 : 1
Thread1 static 7
Thread2 : 2
Thread1 static 8
Thread2 : 3
Thread1 static 9
Thread2 : 4
Thread2 static 0
Thread2 static 1
Thread2 static 2
Thread2 static 3
Thread2 static 4
Thread2 static 5
Thread2 static 6
Thread2 static 7
Thread2 static 8
Thread2 static 9
Thread3 static 0
Thread3 static 1
Thread3 static 2
Thread3 static 3
Thread3 static 4
Thread3 static 5
Thread3 static 6
Thread3 static 7
Thread3 static 8
Thread3 static 9

同步static方法獲取Class對象X上的鎖定,該對象X表示定義方法的類。 在這種情況下, synchronized關鍵字原則上意味着僅在static方法之間進行同步。

而同步實例(非static )方法鎖定調用該方法的當前對象Y

因此,同步static方法和同步實例方法仍然可以交錯,因為它們鎖定了兩個不同的對象。

static方法鎖定/解鎖類( MyRunable )對象,其中非靜態方法鎖定/取消MyRunable對象。 我的意思是,這兩者都不同。

同步方法(第8.4.3.6節)在調用時自動執行鎖定操作; 在鎖定操作成功完成之前,它的主體不會執行。

如果該方法是實例方法,則它會鎖定與調用它的實例關聯的監視器(即,在執行方法主體期間將被稱為this的對象)。

如果方法是靜態的,它將鎖定與Class對象關聯的監視器,該對象表示定義方法的類。

如果方法的主體的執行正常或突然完成,則會在同一監視器上自動執行解鎖操作。

鏈接

暫無
暫無

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

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