确定线程何时结束
1。检查线程是否完成的方法:
isalive()
- 如果线程仍在运行则返回true;否则,返回 false。
- 用于持续检查线程的状态。
加入()
- 使调用该方法的线程等待,直到指定线程完成。
- 有多种变体允许您定义最长等待时间。
2。使用 isalive() 的示例:
// verifica se as threads estão vivas class mythread implements runnable { thread thrd; mythread(string name) { thrd = new thread(this, name); thrd.start(); // inicia a thread } public void run() { system.out.println(thrd.getname() + " starting."); try { for (int count = 0; count < 10; count++) { thread.sleep(400); // suspende a execução por 400ms system.out.println("in " + thrd.getname() + ", count is " + count); } } catch (interruptedexception exc) { system.out.println(thrd.getname() + " interrupted."); } system.out.println(thrd.getname() + " terminating."); } } class morethreads { public static void main(string[] args) { system.out.println("main thread starting."); mythread mt1 = new mythread("child #1"); mythread mt2 = new mythread("child #2"); mythread mt3 = new mythread("child #3"); // verifica se as threads ainda estão vivas do { system.out.print("."); try { thread.sleep(100); } catch (interruptedexception exc) { system.out.println("main thread interrupted."); } } while (mt1.thrd.isalive() || mt2.thrd.isalive() || mt3.thrd.isalive()); system.out.println("main thread ending."); } }
重要要点:
- 主线程不断检查 isalive() 直到所有子线程都完成。
- 线程的执行是由 java 调度的,因此确切的输出可能会有所不同。
3。使用 join() 的示例:
// aguarda o término das threads com join() class mythread implements runnable { thread thrd; mythread(string name) { thrd = new thread(this, name); thrd.start(); // inicia a thread } public void run() { system.out.println(thrd.getname() + " starting."); try { for (int count = 0; count < 10; count++) { thread.sleep(400); // suspende a execução por 400ms system.out.println("in " + thrd.getname() + ", count is " + count); } } catch (interruptedexception exc) { system.out.println(thrd.getname() + " interrupted."); } system.out.println(thrd.getname() + " terminating."); } } class jointhreads { public static void main(string[] args) { system.out.println("main thread starting."); mythread mt1 = new mythread("child #1"); mythread mt2 = new mythread("child #2"); mythread mt3 = new mythread("child #3"); try { mt1.thrd.join(); // aguarda child #1 terminar system.out.println("child #1 joined."); mt2.thrd.join(); // aguarda child #2 terminar system.out.println("child #2 joined."); mt3.thrd.join(); // aguarda child #3 terminar system.out.println("child #3 joined."); } catch (interruptedexception exc) { system.out.println("main thread interrupted."); } system.out.println("main thread ending."); } }
预期输出(可能会有所不同):
Main thread starting. Child #1 starting. Child #2 starting. Child #3 starting. In Child #1, count is 0 In Child #2, count is 0 In Child #3, count is 0 ... Child #1 terminating. Child #1 joined. Child #2 terminating. Child #2 joined. Child #3 terminating. Child #3 joined. Main thread ending.
重要要点:
- join() 确保主线程仅在子线程完成后继续。
- 输出显示每个线程按预期顺序终止。
以上就是确定线程何时结束的详细内容,更多请关注硕下网其它相关文章!