判断多线程如何结束

来源:互联网 发布:电驴端口测试失败 编辑:程序博客网 时间:2024/06/10 23:07

/** * 判断多线程是否全部运行结束的几个方法。 * * @author ,Java世纪网(java2000.net) * */ public class T { public static void main(String[] args) { test1(); test2(); test3(); } /** * join进去,等待线程结束。 */ public static void test1() { System.out.println("test1...................."); MyThread[] threads = new MyThread[10]; for (int i = 0; i < threads.length; i++) { threads[i] = new MyThread(); threads[i].start(); } for (int i = 0; i < threads.length; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("test1 OK"); } /** * 不断的判断线程的状态 */ public static void test2() { System.out.println("test2...................."); MyThread[] threads = new MyThread[10]; for (int i = 0; i < threads.length; i++) { threads[i] = new MyThread(); threads[i].start(); } boolean hasAlive = false; while (true) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } hasAlive = false; for (int i = 0; i < threads.length; i++) { if (threads[i].isAlive()) { hasAlive = true; break; } } if (!hasAlive) { break; } } System.out.println("test2 OK"); } static int threadCount = 0; public static synchronized void finished() { threadCount--; } /** * 借助线程的数量标识 */ public static void test3() { System.out.println("test3...................."); MyThread[] threads = new MyThread[10]; threadCount = threads.length; for (int i = 0; i < threads.length; i++) { threads[i] = new MyThread(); threads[i].start(); } while (threadCount > 0) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("test3 OK"); } } class MyThread extends Thread { public void run() { System.out.println(this.getId() + " is running"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getId() + " is stop"); T.finished(); } }

原创粉丝点击