最初に、消費者ごとに作成することができ、消費者が仕事を終えると、消費者は実行機能を終了して死んでしまうため、無限ループは必要ありません。しかし、消費者ごとにスレッドを作成することは、スレッドの作成がパフォーマンスの点で非常に高価なので、良い考えではありません。スレッドは非常に高価なリソースです。加えて、私はrunnableを実装し、スレッドを拡張しない方が良いという上記の答えに同意します。あなたのスレッドをカスタマイズしたいときにだけスレッドを拡張してください。 スレッドプールを使用することを強くお勧めします。消費者はスレッドプール内のスレッドによって実行された実行可能オブジェクトになります。
public class ConsumerMgr{
int poolSize = 2;
int maxPoolSize = 2;
long keepAliveTime = 10;
ThreadPoolExecutor threadPool = null;
final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
5);
public ConsumerMgr()
{
threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
keepAliveTime, TimeUnit.SECONDS, queue);
}
public void runTask(Runnable task)
{
// System.out.println("Task count.."+threadPool.getTaskCount());
// System.out.println("Queue Size before assigning the
// task.."+queue.size());
threadPool.execute(task);
// System.out.println("Queue Size after assigning the
// task.."+queue.size());
// System.out.println("Pool Size after assigning the
// task.."+threadPool.getActiveCount());
// System.out.println("Task count.."+threadPool.getTaskCount());
System.out.println("Task count.." + queue.size());
}
ない私はあなたの質問を理解してください: コードは次のようになります。このスレッドは本当に永遠に実行されます。永遠に続く状態を使用するかどうかは完全にあなた次第です。 – alf