Java多線程靜態(tài)數(shù)據(jù)如何進行數(shù)據(jù)同步
Java多線程靜態(tài)數(shù)據(jù)在平時的使用中有不少的問題,這些問題需要我們不斷的進行相關(guān)代碼的學(xué)習(xí),下面我們就來看看有關(guān)于Java多線程靜態(tài)數(shù)據(jù)代碼的學(xué)習(xí)。希望大家有所幫助。
1:直接使用靜態(tài)同步方法,Java多線程靜態(tài)數(shù)據(jù)代碼
- public class Foo {
- static int count = 0;
- static public synchronized void inc( int i){
- countcount = count + i; }
- }
- public class Foo {
- static int count = 0;
- static public synchronized void inc( int i){
- countcount = count + i; }
- }
2:使用無關(guān)對象保護靜態(tài)數(shù)據(jù)Java多線程靜態(tài)數(shù)據(jù)代碼
- public class Foo {
- static int count = 0;
- static Object o = new Object();
- public void inc(int i) {
- synchronized(o){
- countcount =count + i; }
- }
- }
- public class Foo {
- static int count = 0;
- static Object o = new Object();
- public void inc(int i) {
- synchronized(o){
- countcount =count + i; }
- }
- }
3:使用Class Itself保護靜態(tài)數(shù)據(jù)Java多線程靜態(tài)數(shù)據(jù)代碼
- public class Foo {
- static int count =0;
- public void inc(int i){
- synchronized(Foo.class) {
- countcount =count + i; }
- }
- }
以上就是對Java多線程靜態(tài)數(shù)據(jù)的相關(guān)介紹。
【編輯推薦】