public class ThreadApp extends Thread {
private Vector queue = new Vector();
private Hashtable ret = new Hashtable();
public ThreadApp() {
this.start();
}
public void run() {
while (true) {
while (queue.size() > 0) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cmd = (String) queue.remove(0);
ret.put(cmd, String.valueOf(System.currentTimeMillis()));
cmd.notify();
cmd = null;
}
}
}
public String fireCommand(String cmd) throws InterruptedException {
queue.add(cmd);
cmd.wait();
return (String) ret.get(cmd);
}
}
这个程序有什么不对
private Vector queue = new Vector();
private Hashtable ret = new Hashtable();
public ThreadApp() {
this.start();
}
public void run() {
while (true) {
while (queue.size() > 0) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cmd = (String) queue.remove(0);
ret.put(cmd, String.valueOf(System.currentTimeMillis()));
cmd.notify();
cmd = null;
}
}
}
public String fireCommand(String cmd) throws InterruptedException {
queue.add(cmd);
cmd.wait();
return (String) ret.get(cmd);
}
}
这个程序有什么不对
cmd.wait();
什么意思? 字符串也可以调用线程方法么?
notify
一般都是和“同步”一起使用的。
cmd.wait();
}
怎么看你的逻辑是反的?主线程你一直在跑着,没有任何wait的迹象,而fireCommand你却wait()?
ps:String这个对象由于实现的差异性,不适合用来wait和notify.
建议你把cmd定义为别的类型,把命令字符串封装起来,
另外这个地方
cmd.notify();
cmd = null;
这两句话中间是不是应该停顿一下,要不执行fireCommand函数的线程可能想要使用cmd时它可能已经没有了
class Commander
{
public void _wait()
{
syn...(this){wait();}
}
public void _notify()
{
syn..(this){notify();}
}
public fireCommand(cmd)
{
//将this和cmd对应一起存入Queue;
_wait();
}
}
在线程中执行时,从Queue中取出cmd和对应的Commander对象,调用commander._notify();
===================
外部请求发送到队列里面---这扮演的是producer的角色
线程里面不停地处理队列里面的请求---这很明显,是consumer吧
而你还有一个queue---老大,一定要记住,这个一定单列一个类出来,然后在producer和consumer里聚合,这样你就能synchronized这个queue类里的put和get方法了,当然你那个queue类里要有一个循环树组或arraylist的,不要用vector,因为方法已经synchronized了。我觉的你会是单一的consumer吧,这样就用wait和notifyAll调节一下,当然了要是想的话可以维护一个consumer的pool。pool不同于waitset,那样会更牛逼一些。我以前老想写个关于pool的http请求的处理的文章,没想到今天被你提起来。
那用Vector不是更简单吗?不懂,指教