假设main启动了3个A线程,3个B线程现在希望 这6个线程执行完后,然后main方法在接下去执行,有什么简单的方法没有自己实现了一个,感觉很繁琐
package threadTest;public class TestThread { /**
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub Counter counter = new Counter();
Thread t1 = new Thread(new Adder(counter));
Thread t2 = new Thread(new Adder(counter));
Thread t3 = new Thread(new Adder(counter)); Thread t4 = new Thread(new Subtracter(counter));
Thread t5 = new Thread(new Subtracter(counter));
Thread t6 = new Thread(new Subtracter(counter)); t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start(); // CyclicBarrier cb = new CyclicBarrier(6); synchronized (counter) {
while (Counter.getCondition() < 6) {
// System.out.println(Counter.getCondition());
counter.wait();
}
} System.out.println(Counter.getId());
System.out.println("main end"); }}class Adder implements Runnable { private Object o; public Adder(Object o) {
this.o = o;
} @Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10000; i++)
Counter.addId();

synchronized (o) {
Counter.addCondition();
System.out.println(Thread.currentThread().getName() + " end");
if (Counter.getCondition() == 6)
o.notify();
} }}class Subtracter implements Runnable { private Object o; public Subtracter(Object o) {
this.o = o;
} @Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 1000; i++)
Counter.subtractId(); synchronized (o) {
Counter.addCondition();
System.out.println(Thread.currentThread().getName() + " end");
if (Counter.getCondition() == 6)
o.notify();
} }}class Counter {
private static int id = 1000;
private static int condition = 0; public synchronized static int getCondition() {
return condition;
} public synchronized static void addCondition() {
condition++;
System.out.println("condition=" + condition);
} public static void addId() {
id++;
} public static void subtractId() {
id--;
} public static int getId() {
return id;
} public static void setId(int id) {
Counter.id = id;
}}

解决方案 »

  1.   

    线程的join()方法,楼主可以去查查
      

  2.   

    不知道join方法的原理是什么,是不是使用同步机制...
      

  3.   

    看看源码:
     public final synchronized void join(long millis)
        throws InterruptedException {
            long base = System.currentTimeMillis();
            long now = 0;        if (millis < 0) {
                throw new IllegalArgumentException("timeout value is negative");
            }        if (millis == 0) {
                while (isAlive()) {
                    wait(0);
                }
            } else {
                while (isAlive()) {
                    long delay = millis - now;
                    if (delay <= 0) {
                        break;
                    }
                    wait(delay);
                    now = System.currentTimeMillis() - base;
                }
            }
        }