简体   繁体   English

sqlite4java 多线程支持解决方案

[英]sqlite4java multithread-support solution

I'm trying to implement a Java Swing GUI App with a game.我正在尝试用游戏实现 Java Swing GUI App。 The game is to count how many times a button is clicked in 5 seconds.游戏是计算一个按钮在 5 秒内被点击了多少次。

I'm using sqlite4java in one of my Java GUI projects.我在我的 Java GUI 项目之一中使用sqlite4java It is pretty minimalistic therefore supports only single-threaded apps.它非常简约,因此仅支持单线程应用程序。

I want to execute some SQL query after the 5 seconds is up.我想在 5 秒后执行一些 SQL 查询。 I have a Thread started in my button's onclick listener whose run() method is implemented like the following:我在按钮的 onclick 侦听器中启动了一个线程,其 run() 方法的实现如下:

run() {
 timeLeft = 5;
 score = 0;
 while(timeLeft>0)
      Thread.sleep(100);
      timeLeft -= 0.1;
      update left time on GUI;
  }
  // time is up
  execute some SQLite INSERT query here;
}

And since sqlite4java is single-thread supported, it throws an exception:而且由于 sqlite4java 是单线程支持的,它会抛出一个异常:

SQLite error:com.almworks.sqlite4java.SQLiteException:
[-98] DB[1] confined(Thread[main,5,]) used (Thread[Thread-3,6,main]) 

How can I possibly execute after thread is finished (outside the thread)?线程完成后(线程外)我怎么可能执行? It is throwing an exception because the callee thread and the thread in which database is instantiated (Main thread) are not the same.它抛出异常是因为被调用线程和实例化数据库的线程(主线程)不同。

How can I make main thread signaled (and handle this signal in main thread) after this thread terminates?在此线程终止后,如何使主线程发出信号(并在主线程中处理此信号)?

All I want to achieve is to execute query to add user's score to high scores list.我想要实现的只是执行查询以将用户的分数添加到高分列表中。 That's not an homework, I'm trying to develop a proof-of-concept application for my own ORM framework.这不是功课,我正在尝试为我自己的 ORM 框架开发一个概念验证应用程序。

As @corlettk advises, you need to have a separate thread for database operations.正如@corlettk 建议的那样,您需要有一个单独的线程来进行数据库操作。 sqlite4java comes with SQLiteQueue, which does that for you. sqlite4java 带有 SQLiteQueue,它会为你做这件事。 There's a tutorial and javadoc with example .有一个教程带有示例的 javadoc

Make sure you wrap ALL database operations with SQLiteJob(s) and pass them to the queue.确保使用 SQLiteJob(s) 包装所有数据库操作并将它们传递给队列。

Hope this helps!希望这可以帮助! Igor伊戈尔

Ahmet,艾哈迈德,

I guess you'll have to do ALL your "database stuff" (including dis/connect) on ONE thread, which should probably be dedicated to this purpose;我想您必须在一个线程上完成所有“数据库工作”(包括断开/连接),这可能应该专门用于此目的; maybe even "hidden" behind a request-queue.甚至可能“隐藏”在请求队列后面。

Good luck with that.祝你好运。 Can you "just" swap RDBMS's instead?你可以“只是”交换 RDBMS 吗?

Cheers.干杯。 Keith.基思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM