关于线程,继续讨论,gemouzhi(gemouzhi)请进,
孙亖
领域专家: 前端开发技术领域 2005-11-04 01:53:23 原贴:http://community.csdn.net/Expert/TopicView3.asp?id=4371270
public class Test {
public static void main(String[] args) {
try {
ThreadApp ta = new ThreadApp();
for (int i = 0; i < 5; i++) {
new Consumer(String.valueOf(i), ta);
System.err.println(" " + i);
System.err.println(" ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(1);
}
}
class Consumer extends Thread {
private ThreadApp ta = null;
private String id = null;
public Consumer(String id, ThreadApp ta) {
this.id = id;
this.ta = ta;
this.start();
}
public void run() {
try {
ta.fireCommand(id + " : " + String.valueOf(System.currentTimeMillis()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.util.Hashtable;
import java.util.Vector;
public class ThreadApp extends Thread {
private Vector queue = new Vector();
private Hashtable ret = new Hashtable();
public ThreadApp() {
this.start();
System.out.println("currentThread in construt ThreadApp : " + Thread.currentThread());
}
public void run() {
System.out.println("currentThread in run : " + Thread.currentThread());
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()));
synchronized (cmd) {
cmd.notify();
}
cmd = null;
}
}
}
public String fireCommand(String cmd) throws InterruptedException {
System.out.println("currentThread in fireCommand : " + Thread.currentThread());
String innerCmd = cmd + System.currentTimeMillis();
queue.add(innerCmd);
synchronized (innerCmd) {
innerCmd.wait();
}
System.out.println("innerCmd is " + innerCmd);
String rv = (String) ret.get(innerCmd);
System.out.println("return value is " + rv);
return rv;
// return (String) ret.get(innerCmd);
}
}