这是个挺有趣的程序,我写了个例子同步了10个子线程,可以参考下: public class Test { static Test test = null; static int childNum = 0; synchronized static void decSem(){ childNum--; if(childNum == 0){ synchronized(test){ test.notify(); } } }
Test(){ test = this; } void connectDB() throws InterruptedException{ synchronized(this){ childNum = 10; new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); new TestThread().start(); wait(); } } public static void main(String[] args) throws InterruptedException { System.out.println("Start..."); Test test = new Test(); test.connectDB(); System.out.println("End."); } }
class TestThread extends Thread{ public void run() { super.run(); System.out.println("child thread"); Test.decSem(); } }

|