加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-12 20:07:18 所属栏目:百科 来源:https://code.google.com/p/sqli
导读:sqlite4java是sqlite驱动的一个开源项目,效率和稳定性非常的不错,关键是它在各个平台下均有本地实现,跨平台做的很不错,使用也非常的简单,又能提供x86平台和arm平台的支持,windows、linux、安卓全面支持,该项目官方网站: https://code.google.com/p/s

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

最新版本:

sqlite4java-282withSQLite 3.7.10and 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<Boolean>() {
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();
}

//结束

}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读