如何通过多个线程将数据存储在MySql中? [英] How to store data in MySql through multiple threads?

查看:75
本文介绍了如何通过多个线程将数据存储在MySql中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从main()函数开始了五个线程.

I have started five threads from main() function.

我编写了以下三个函数:

I have written three functions as follows:

getConnectionToDatabase();
saveToDataBase();
closeConnection();

现在,我希望主函数应该在通过调用getConnectionToDataBase()启动这五个线程之前建立与数据库的连接,这样每个线程都不必启动新的连接.

Now I want that main function should establish a connection to the database before starting those five threads by calling getConnectionToDataBase() so that each thread doesn't have to start a new connection.

现在,我希望每个线程都应该通过首先获取由main()函数建立的连接来调用saveToDataBase()来存储数据.

Now I want that each thread should store the data by calling saveToDataBase() by first getting the connection established by the main() function.

我该怎么做?

如有需要,我可以提供其他信息.

I can provide additional information if you need any.

推荐答案

这样做不是一个好主意. (感谢ChssPly76指出我的错误和较差的内存.)

It's a bad idea to do this. (Thanks to ChssPly76 for pointing out my error and poor memory.)

但是,如果必须的话,让主类创建连接并将其传递给实现Runnable的每个类的构造函数.执行数据库工作的类将具有引用Connection的私有数据成员.然后,主类在完成连接后将其关闭.

But if you must, have the main class create the connection and pass it to the constructor of each class that implements Runnable. The class that does the database work will have a private data member that references the Connection. Then the main class closes the Connection when they're done.

更好的设计是每个线程有一个Connection,并带有一个Connections池,但这是您的选择.

A better design is one Connection per thread with a pool of Connections, but it's your choice.

这篇关于如何通过多个线程将数据存储在MySql中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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