Java中,正确使用静态变量prevent僵局 - 同步 [英] java ,Properly using Static variables to prevent deadlock - Synchronizing

查看:203
本文介绍了Java中,正确使用静态变量prevent僵局 - 同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid编程和'前已经没有研究透的Java。我真的很困惑如何使用同步来确保静态变量线程安全的:

I am new to android programming and 've not thoroughly studied java before . I am really confused on how to use synchronized to ensure thread safety on static variables :

我通常会创建一个名为 utils的类,它有一定的静态函数这是大多数的所有所需的时间我的其他类。这是保持重复code我的课​​的正确途径。

I usually create a class named Utils which has some static functions which are most of the time needed by all my other classes. Is this the correct way of keeping repetitive code out of my classes.

我总是苦于使用数据库的问题。当我创建了某些数据库sqliteHelper类,并试着从说,一个活动和一个后台服务来管理数据库,我通常会
陷入麻烦。如果我使用辅助类的局部对象,我要进入数据库的死锁最大时容易出现两个辅助对象试图获取写锁在一起。

I always suffer from a problem with using Databases. When I create sqliteHelper class for certain Database and try to manage that database from say an Activity and a Background service , I usually get into trouble. If I use local objects of helper class , I am maximum prone to getting into deadlocking of database when both the helper objects try to acquire write lock together.

有关走出这个困境,我创建一个静态在我的 utils的类的辅助类的实例。现在对数据库进行任何操作我的活动,我的服务做以下的事情:

For getting out of this trouble , I create a static instance of the helper class in my utils class. Now for performing any operation on database my activity and my service do the following thing :

   public class Utils{
          public static MDatabaseHelper mHelper;
          public static void instantiateHelper(Context context){
          if(mHelper==null)
                mHelper=new MDatabaseHelper(context);

           }
    } 



    public class mActivity extends Activity{
     public void insert some item in database(final Item item)   // this method is called in the Activity at some time
     (new Thread(){
         @Override public void run(){
         Utils.instantiateHelper(getBaseContext());
         mHelper.insertItem(item); }
        }).start();
     }




 public class mService extends Service{
         public void insert some item in database(final Item item)    // this method is called in the service at some time
          (new Thread(){
           @Override public void run{
             Utils.instantiateHelper(getBaseContext());
             mHelper.insertItem(item); }
        }).start();
     }

现在什么如果这两个服务和活动尝试一起插入项目。我经常陷入这种状况,就会发生错误。
为了避免这种情况我使用此解决方法:

Now what if both the service and the activity try to insert the item together. I oftentimes get into this situation and an error occurs . To avoid this I use this workaround :

我把插入操作try块,失败我等待随机的时间,然后重试。

I put the insert operation in a try block and on failure I wait for random time and try again

    public void insertSomeItemInDatabase(final Item item)
     (new Thread(){
          @Override public void run(){
              int i=0;
              Random rand=new Random();
                 while(true){
                  if(i>10)
                    return;
                  try{ 
                     Utils.instantiateHelper(getBaseContext());
                     mHelper.insertItem(item);
                     break;
                     }catch(Exception e){
                      i++;
                           try{
                              Thread.sleep(rand.nextInt(1000));
                               }catch(Exception e){}
                      }

                      }
          } 
          }
        }).start();
     }

我知道这是在最坏的同步,但由于我很新的Java 任何一个可以请解释如何使用<方法code>在这种情况下同步。

I know this is the Worst method of synchronizing but since I am so new to java can any one please explain how to use synchronized in this Scenario .

感谢您

推荐答案

我觉得你所有的需要的是创造的应用类

I think all your need is to create Application Class

[1] 您已经采取的Util这是在所有其他类使用的所有这些变量,可以采取这个应用程序类。因此,这些变量将提供给所有其他类。

[1] All those variables you have taken in Util, which are used in about all other class, can be taken in this Application class. So these variables will be available to all other classes.

[2] 创建的机应用类 Singelton实例。只是谷歌一下吧。

[2] Create Singelton instance of Appliction class. Just Google about it.

[3] 同时创建DataBaseHelper的辛格尔顿(如果可能的话,可以申请),因此,单实例可以帮助你每一个地方。

[3] Also create Singleton of DataBaseHelper(if possible and can apply), so, single instance helps you every where.

应用程序类是Android的全球一流的,所以你可以用它来存储和访问所有全局数据。例如

Application Class is Global class in android, so you can use it to store and access all Global-Data. e.g. :

public class AppData extends Application {

    public static AppData appData;

    public int currentUserId; // etc.

    //Const.
    public AppData() {
        appData = this;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        loginPreferences = getSharedPreferences(
            SPF_NAME, 0);

        pathToSDCard = Environment.getExternalStorageDirectory().getAbsolutePath();
        System.out.println("Path : " + pathToSDCard);
       //etc.
    }

 //    MOST IMP  FOR GETTIN SINGELTON INSTANCE     <<<---<<<---<<<---
    public static AppData getAppData() {
        return appData;
    }
}

如何使用它,请参阅本

class ABC extends Activity {
    AppData appData;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xyz);

        appData = AppData.getAppData();
        ...........
        ...........

        appData.VARIABLE_NAME...
    }
}

还有一件事。在AndroidMenifest.xml

    ...
    ...
<application             //   In Application Tag
        android:name="PACKAGE_NAME.AppData"  //  <<  Add here class name in which you have extended Application
        android:icon="@drawable/ic_launcher"
    ...
    ...

这篇关于Java中,正确使用静态变量prevent僵局 - 同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆