public class MyCountDown { private int count; public MyCountDown(int count){ this.count = count; } public synchronized void countDown(){ count--; } public synchronized boolean hasNext(){ return (count > 0); } public int getCount() { return count; } public void setCount(int count) { this.count = count; } } |
ImportThread类
public class ImportThread extends Thread {
|
public class ImportThread extends Thread { private MyCountDown c; public ImportThread(MyCountDown c) { this.c = c; } @Override public void run() { System.out.println(Thread.currentThread().getName() + "开始...");//打印开始标记 //Do something c.countDown();//计时器减1 System.out.println(Thread.currentThread().getName() + "结束. 还有" + c.getCount() + " 个线程");//打印结束标记 } } |
主线程中
System.out.println(Thread.currentThread().getName() + "开始");//打印开始标记
|
System.out.println(Thread.currentThread().getName() + "开始");//打印开始标记 MyCountDown c = new MyCountDown(threadNum);//初始化countDown for (int ii = 0; ii < threadNum; ii++) {//开threadNum个线程 Thread t = new ImportThread(c); t.start(); } while(true){//等待所有子线程执行完 if(!c.hasNext()) break; } System.out.println(Thread.currentThread().getName() + "结束.");//打印结束标记 |