日期:2014-05-20  浏览次数:20705 次

main线程如何在其内部的所有执行完后在执行接下来的步骤
假设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;
}

}