我有一个对象,用于使用多线程方法更新数据库。
现在,我不想因为更新尝试而导致数据库连接崩溃,并且希望在有一定数量的 Activity 线程时等待。
我的类(class)implements Runnable
称为 updateUnmarked
.
现在,我只想在我的线程数为 < X
时启动一个新线程
Thread.getAllStackTraces().keySet().size()
似乎不起作用,而且以下似乎也不能解决它:
public static int getLiveThreads(){
ThreadMXBean bean = null;
bean = ManagementFactory.getThreadMXBean();
return bean.getThreadCount();
}
都只返回 8...但我肯定有超过 8 个线程。
知道如何做到这一点吗?
谢谢!!!
最佳答案
now, i want to only launch a new thread if my thread count is < X
在我看来,您需要的是一个线程池执行器。对数据库的更新可以提交到池中执行,并且您可以通过限制分配给池的线程数来限制对数据库的并发请求数:
// create a thread pool with a max of 4 concurrent threads
ExecutorService threadPool = Executors.newFixedThreadPool(4);
// submit your database operation to the thread-pool
threadPool.submit(new DatabaseUpdateJob(databaseConnection, updateStatement));
...
public class DatabaseUpdateJob implements Runnable {
// you can construct your jobs and pass in context for them if necessary
public DatabaseUpdateJob(Connection dbConnection, String statement) {
...
}
public void run() {
// use the connection here to update the database
}
}
如果你真的想自己做,那么 Thread.activeCount()
肯定可以工作。它返回当前线程组中 Activity 线程的数量。您需要做的是在开始数据库工作之前拍摄线程数的快照。有许多系统线程在后台运行,执行您应该忽略的各种任务。然后,每当您进行新计数时,您都可以减去后台线程并仅跟踪数据库线程。
但是线程池总是一个好主意。
关于Java获取线程实例的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790828/