Thread
またはThreadGroup
インスタンスをその名前で終了するにはどうすればよいですか?
質問する
6235 次
2 に答える
5
このようなもの
Thread[] a = new Thread[1000];
int n = Thread.enumerate(a);
for (int i = 0; i < n; i++) {
if (a[i].getName().equals(name)) {
a[i].interrupt();
break;
}
}
interrupt() はスレッドを終了しませんが、stop() は終了します (非推奨ですが)
于 2013-03-20T16:26:34.353 に答える
3
It depends on what do you mean when you say "terminate".
But first tip is that you have to get a list of all threads to terminate. Use Thread.getThreads()
to do this. You can filter threads by their group if needed.
Now, how to stop the thread? There are 2 ways.
- call
stop()
method. It is deprecated and you should never use it because it might cause system to enter inconsistent state. However, if you really want ... this method is still supported. - Every thread should support shutdown mechanism, i.e. a "protocol" that can be used to signal thread to exit its
run()
method. If all threads are yours you can make them to implement your own interface (e.g.Terminatable
) with methodterminate()
that will change value of flag and cause thread to exit. In this case your code that terminates threads should iterate over threads, check that thread should be terminated and that it implements interfaceTerminatable
, cast to it and call itsterminate()
method.
于 2013-03-20T16:44:56.327 に答える