判断多线程如何结束

/** * 判断多线程是否全部运行结束的几个方法。 * * @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(); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值