sqlite4java中的多线程队列使用(线程安全)

sqlite4java是sqlite驱动的一个开源项目,效率和稳定性非常的不错,关键是它在各个平台下均有本地实现,跨平台做的很不错,使用也非常的简单,又能提供x86平台和arm平台的支持,windows、linux、安卓全面支持,该项目官方网站:https://code.google.com/p/sqlite4java/

最新版本:

sqlite4java-282 with SQLite 3.7.10 and Android support

但是关于其中多线程下确保安全的队列:

SQLiteQueue官方网站的介绍非常的少,下面就举例说明它的用法:

测试主程序:

public class Mainapp {


 
 /**
  * @param args
  * @throws SQLiteException
  * @throws InterruptedException
  * @throws IOException
  */
 public static void main(String[] args) throws SQLiteException, IOException, InterruptedException {
  SQLiteQueue myQueue=new SQLiteQueue(new File(file_db));
  myQueue.start();
 

//主线程一定要建立唯一的   SQLiteQueue,这个队列已经打开好数据库,在myQueue.start();

//后,就在其他任何线程可以往队列里加入数据库操作(SQLiteJob),当然主线程也是可以的。

  Sql_thread sql_thread1=new Sql_thread(myQueue);
  Thread t1=new Thread(sql_thread1);

  Sql_thread sql_thread2=new Sql_thread(myQueue);
  Thread t2=new Thread(sql_thread2);

 

//******启动线程
       
t1.start();
t2.start();
   }
}

//*************************************sql操作线程*****************************************************

public class Sql_thread implements Runnable{
 private SQLiteQueue myQueue;
 public Sql_thread (SQLiteQueue myQueue) {
  this.myQueue=myQueue;
  }
 @Override
 public void run() {

   for (int i=0;i<1000;i++) {
     insert_Record("插入1", “插入2”);   //  本地有查询方法就不用传入myQueue,否则参数里需要带上myQueue直到传递到sqlite操作方法里

   }

 }

//********************************写数据库**************************************************************

 public static Boolean insert_Record (final String cardno,final String card_type)  {       
    return myQueue.execute(new SQLiteJob() {
    protected Boolean job(SQLiteConnection connection) throws SQLiteException {
        SQLiteStatement st = connection.prepare("insert into record(cardno,card_type) values (?,?)");
        try {
          st.bind(1, cardno);
          st.bind(2, card_type);  
          st.step();
          return true;
        } finally {
          st.dispose();
        }
      }
    }).complete();
  }

//结束

}

如果有什么疑问可以留言。


 

 

   

 

你可能感兴趣的:(sqlite,java,sqlite4java)