考虑这个示例类:
public class Multithreading extends Thread {
static int i = 0;
public static void main(String args[]) throws InterruptedException {
call1();
call2();
}
private static void call2() {
Multithreading call2obj1 = new Multithreading() {
public void run() {
}
};
call2obj1.start();
}
private static void call1() {
Multithreading call1obj1 = new Multithreading() {
public void run() {
System.out.println("call1obj1");
sleep(5000);
}
};
Multithreading call1obj2 = new Multithreading() {
public void run() {
System.out.println("call1obj2");
sleep(5000);
}
};
call1obj1.start();
call1obj2.start();
}
}
我希望call2()
等待call1()
完全完成。即,call1obj2
不需要等到call1obj1
执行完毕,但call2obj1
应该等到call1obj1
和call1obj2
都完成。
基本上call1obj1
和call1obj2
的主题行为必须限于call1()
;
这可能吗?
答案 0 :(得分:1)
以下是使用CountDownLatch的解决方案:
public class Multithreading extends Thread {
static int i = 0;
private static CountDownLatch LATCH;
public static void main(String args[]) throws InterruptedException {
// Initialize the latch with the number of threads to finish
LATCH = new CountDownLatch(2);
call1();
// Main thread will wait until all thread finished
LATCH.await();
call2();
}
private static void call2() {
Multithreading call2obj1 = new Multithreading() {
public void run() {
System.out.println("call2obj1");
}
};
call2obj1.start();
}
private static void call1() {
Multithreading call1obj1 = new Multithreading() {
public void run() {
System.out.println("call1obj1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
LATCH.countDown();
}
}
};
Multithreading call1obj2 = new Multithreading() {
public void run() {
System.out.println("call1obj2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
LATCH.countDown();
}
}
};
call1obj1.start();
call1obj2.start();
}
}