使用执行人,所推荐的其他人。然而,如果你想自己做这件事的乐趣,尝试这样的事情。 (小心点,我用记事本写了,有一些例外情况,即使我把所有其他东西都记下来,记事本在编码错误方面的表现也很差。)这是一个概念,而不是实际解决任何问题的方法,但这个想法可能通常是有用的。
private ConcurrentLinkedQueue<MyThread> tQueue =
new ConcurrentLinkedQueue<MyThread>();
class MyThread extends Thread {
public Runnable doSomething;
public void run() {
// Do the real work.
doSomething();
// Clean up and make MyThread available again.
tQueue.add(mythread);
// Might be able to avoid this synch with clever code.
// (Don't synch if you know no one's waiting.)
// (But do that later. Much later.)
synchronized (tQueue) {
// Tell them the queue is no longer empty.
tQueue.notifyAll();
}
}
}
在别处:
// Put ten MyThreads in tQueue.
for (int i = 0; i < 10; i++) tQueue.add(new MyThread());
// Main Loop. Runs ten threads endlessly.
for (;;) {
MyThread t = tQueue.poll();
if (t == null) {
// Queue empty. Sleep till someone tells us it's not.
do {
// There's a try-catch combo missing here.
synchonized(tQueue) { tQueue.wait() };
t = tQueue.poll();
} while (t == null) break; // Watch for fake alert!
}
t.doSomething = do_some_work;
t.start();
}
另外,还要注意巧妙利用的ConcurrentLinkedQueue的。你可以使用其他的东西,比如ArrayList或者LinkedList,但是你需要同步它们。
http://docs.oracle.com/javase/7/docs/api/java/util /concurrent/BlockingQueue.html将是完美的工作 – bkowalczyyk 2015-07-21 12:40:06