我有以下套接字连接代码。每个连接的位置是一个新线程。在收到通过生产者完成的数据之后,我将一个队列放入下一个数据库处理器,即消费者。这样可以正常运行,但是当队列建立起来时,它可能会挂起甚至需要几个小时来清除原因,就像许多生产者和只有一个消费者一样。我想我有可能让一个消费者处理一个生产者,这意味着每个消息进入自己的队列获取进程和它。我可以做些什么更改来处理它,还是必须构建一个线程池?
public class cServer {
private LinkedBlockingQueue<String> databaseQueue = new LinkedBlockingQueue<String>();
class ConnectionHandler implements Runnable {
private Socket receivedSocketConn1;
ConnectionHandler(Socket receivedSocketConn1) {
this.receivedSocketConn1=receivedSocketConn1;
}
// gets data from an inbound connection and queues it for databse update
public void run() { // etc
// you already have most of this in your existing code.
// it uses the shared databaseQueue variable to queue message Strings
BufferedWriter w = null;
BufferedReader r = null;
String message="";
try {
PrintStream out = System.out;
BufferedWriter fout = null;
w = new BufferedWriter(new OutputStreamWriter(receivedSocketConn1.getOutputStream()));
r = new BufferedReader(new InputStreamReader(receivedSocketConn1.getInputStream()));
int m = 0, count=0;
int nextChar=0;
while ((nextChar=r.read()) != -1)
{
message += (char) nextChar;
if (nextChar == '*')
{
databaseQueue.add(message);
message="";
}
}
}
catch (IOException ex)
{
System.out.println("MyError:IOException has been caught in in the main first try");
ex.printStackTrace(System.out);
}
finally
{
try
{
if ( w != null )
{
w.close();
}
else
{
System.out.println("MyError:w is null in finally close");
}
}
catch(IOException ex){
System.out.println("MyError:IOException has been caught in w in finally close");
ex.printStackTrace(System.out);
}
}
}
}
class DatabaseProcessor implements Runnable {
// updates databaase with data queued by ConnectionHandler
Connection dbconn = null;
Statement stmt = null;
Statement stmt1 = null;
Statement stmt2 = null;
Date connCreated = null;
public void run()
{ // this is just like the QueueProcessor example I gave you
// open database connection
//createConnection();
while (true)
{
try
{
int count=0;
String message = "";
message = databaseQueue.take();
if (message.equals(null)) {
System.out.println("QueueProcessor is shutting down");
break; // exit while loop, ends run() method
}
System.out.println("Message taken from queue is :"+message);
}
catch (Exception e)
{
e.printStackTrace();
}
}//while true
//closeConnection();
}//run
}
public static void main(String[] args) {
new cServer();
}
cServer() { // default constructor
new Thread(new DatabaseProcessor()).start();
try
{
final ServerSocket serverSocketConn = new ServerSocket(5000);
while (true)
{
try
{
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
}
catch(Exception e)
{
System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
}
}
}
catch (Exception e)
{
System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
e.printStackTrace(System.out);
//System.exit(0);
}
databaseQueue.add(null);
}
}