【发布时间】:2013-11-20 22:25:19
【问题描述】:
我需要创建一个回显服务器来回显请求的字符串。一个线程(客户端)调用 echo 方法来提交要回显的字符串(所有 echo 方法实际上所做的就是将字符串放入作业队列中),然后一个单独的线程从队列中取出字符串并将它们输出到屏幕。
其中一个步骤是使队列静态化,以便在线程之间共享它,我通过简单地替换来做到这一点:
public final Queue<String> requests = new LinkedList<String>();
with(不确定是否正确)
public static Queue<String> requests = new LinkedList<String>();
在这段代码中:
public class EchoServer implements Runnable {
//make queue a static object
//public final Queue<String> requests = new LinkedList<String>();
public static Queue<String> requests = new LinkedList<String>();
public EchoServer() {
new Thread(this).start();
}
//all echo does is place the string in the job queue
public void echo(String s) {
requests.add(s);
}
public void run() {
for(;;) realEcho(requests.remove());
//synchronized here?
}
private void realEcho(String s) {
// do the real work of echo-printing
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
EchoServer r1 = new EchoServer();
r1.echo("HEY");
Thread t1 = new Thread(r1, "manager");
t1.start();
EchoServer r2 = new EchoServer();
r2.echo("HI");
Thread t2 = new Thread(r2, "client");
t2.start();
}
}
我现在的问题(除了“NoSuchElement”异常,这是因为每个线程都试图从请求队列中删除元素而不添加任何内容)是我需要处理同步问题,因为队列在多个线程之间共享.当我试图弄清楚同步时,我很迷茫。有没有人有一些可以帮助我的提示?任何帮助表示赞赏!
【问题讨论】:
标签: java multithreading synchronization queue echo