thread.stop、thread.suspend、thread.resume、runtime.runfinalizersonexitこれらのスレッドを終了する方法は放棄されており、それらを使用することは非常に安全ではありません!
1.スレッドは正常に実行され、通常は終了します
つまり、実行方法を実行すると、スレッドが正常に終了します。
しかし、時にはスレッドが終わることはありません。
2。特定の条件を監視し、途切れないスレッド操作を終了します
while()ループは、特定の条件で終了する必要があります。最も直接的な方法は、ブールフラグを設定し、このフラグを設定してループが出るかどうかを制御することです。
public class threadflagはスレッドを拡張します{public volatile boolean exit = false; public void run(){while(!exit){system.out.println( "running!"); }} public static void main(string [] args)スロー例外{threadflag thread = new threadflag(); thread.start();睡眠(1147); //メインスレッドは5秒遅れましたthread.exit = true; //スレッドスレッドスレッドを終了しますjoin(); system.out.println( "スレッドexit!"); }}3.割り込み方法を使用して、スレッドを終了します
スレッドがブロックしている場合、方法2を使用してスレッドを終了できません。
public class threadinterruptはスレッド{public void run(){try {sleep(50000); // 50秒遅延} catch(arternedexception e){system.out.println(e.getmessage()); }} public static void main(string [] args)throws exception {thread thread = new threadinterrupt(); thread.start(); System.out.println( "50秒以内に任意のキーを押して、スレッドを中断します!"); system.in.read(); thread.interrupt(); thread.join(); system.out.println( "スレッドが終了!"); }}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。