關於靜態方法和非靜態方法 類鎖和物件鎖

2021-09-23 23:58:18 字數 1519 閱讀 2690

劃重點

static方法是類中的乙個成員方法,屬於整個類,即使不用建立任何物件也可以直接呼叫!

靜態方法效率上要比例項化高,靜態方法的缺點是不自動進行銷毀,而例項化的則可以做銷毀。

靜態方法和靜態變數建立後始終使用同一塊記憶體,而使用例項的方式會建立多個記憶體。

在靜態方法或者方法塊上加的鎖為類鎖 (鎖類)

非靜態方法為物件鎖(鎖物件)

詳細如下  

類鎖 (鎖類):

public class statictest 

}public synchronized static void fun2() throws interruptedexception

}public static void main(string args) catch (interruptedexception e)

});statictest statictest2 = new statictest();

thread t2 = new thread(() -> catch (interruptedexception e)

});t1.start();t2.start();

}}

會發現

會一直把乙個fun 內容全部執行完 才會去執行另外乙個fun的內容

物件鎖

public class statictest 

}public synchronized void fun2() throws interruptedexception

}public static void main(string args) catch (interruptedexception e)

});statictest statictest2 = new statictest();

thread t2 = new thread(() -> catch (interruptedexception e)

});t1.start();t2.start();

}}

不同物件的fun方法  

出現交替列印 未鎖住

public class statictest 

}public synchronized void fun2() throws interruptedexception

}public static void main(string args) catch (interruptedexception e)

});statictest statictest2 = new statictest();

thread t2 = new thread(() -> catch (interruptedexception e)

});t1.start();t2.start();

}}

會發現

會一直把乙個fun 內容全部執行完 才會去執行另外乙個fun的內容  鎖住了該物件

靜態方法和非靜態方法

首先,兩者本質上的區別是 靜態方法是在類中使用staitc修飾的方法,在類定義的時候已經被裝載和分配。而非靜態方法是不加static關鍵字的方法,在類定義時沒有占用記憶體,只有在類被例項化成物件時,物件呼叫該方法才被分配記憶體。其次,靜態方法中只能呼叫靜態成員或者方法,不能呼叫非靜態方法或者非靜態成...

靜態方法和非靜態方法

靜態方法和非靜態方法 其次,靜態方法中只能呼叫靜態成員或者方法,不能呼叫非靜態方法或者非靜態成員,而非靜態方法既可以呼叫靜態成員或者方法又可以呼叫其他的非靜態成員或者方法。例子1 靜態方法的main方法訪問類中的非靜態成員方法。class test public static void main s...

靜態和非靜態方法 呼叫靜態和非靜態方法 原創

在學習php物件導向的時候,遇到了一些問題 class test1 在test1類中,定義了乙個test方法。一般呢,想要呼叫test方法的話,是通過例項化乙個物件來呼叫test方法的。比如 aaa.php php 正常的方式訪問普通方法test class test1 new new test1 ...