【发布时间】:2016-12-05 16:33:29
【问题描述】:
我正在做一个项目,对于我的项目的一部分,我有一个字符串数组列表,我记录在案,以保存来自其他互连系统的传入消息。这是一个点对点的设计,所以我想让一个 BufferedReader 准备好读取从任何套接字发送到系统的任何消息,所以我设计了一个线程,在创建时为每个套接字创建一个新线程,该线程将监听特定的输入溪流。
现在我已经尝试使用以下两个私有类:
InputListener(内部类ListenerThread)
private class InputListener implements Runnable{
private ArrayList<String> queue;
private ArrayList<Stream> sockets;
private ArrayList<Thread> threads;
public InputListener(ArrayList<String> q, ArrayList<Stream> s)
{
this.queue = q;
this.sockets = s;
this.threads = new ArrayList<Thread>();
for(int i = 0; i < this.sockets.size(); i++)
{
Thread t = new Thread(new ListeningThread(this.sockets.get(i).is, this.queue));
t.start();
threads.add(t);
}
}
private class ListeningThread implements Runnable{
private BufferedReader read;
private ArrayList<String> queue;
private boolean status;
public ListeningThread(InputStream is, ArrayList<String> q)
{
this.read = new BufferedReader(new InputStreamReader(is));
this.queue = q;
status = true;
}
@Override
public void run() {
while(true)
{
String str = "";
try {
str += read.readLine();
while(!str.equals("END"))
str += read.readLine();
this.queue.add(str);
} catch (IOException e) {
status = false;
break;
}
}
}
}
@Override
public void run() {
while(status)
;
}
}
流
private class Stream{
public InputStream is;
public OutputStream os;
public Stream(final Socket s)
{
try {
this.is = s.getInputStream();
this.os = s.getOutputStream();
} catch (IOException e) {
return;
}
}
public InputStreamReader getReader()
{
return new InputStreamReader(this.is);
}
}
当我创建 InputListener 时,我从另一个类传递了对队列的引用,我排除了这个类以防止这个问题过于复杂,所以假设这个 ArrayList 已经初始化并且它是指针(我不记得 java 叫什么了)已通过。我的问题是,当我使用如下循环时,我只是陷入了无限循环
while(queue.size equals 0)
Do nothing
Remove and do something with String at index 0 in queue
谁能帮我解决这个问题?任何帮助将不胜感激!
【问题讨论】:
-
你能根据提供的答案解决这个问题吗?
标签: java multithreading sockets arraylist reference