两种方案:
1>利用Thread.join()方法,使C进程等待AB进程完成后执行
2>利用CountdownLatch定义一个计数器,在AB进程里用CountdownLatch. countDown()方法使计数器减少,在等待进程C中使用CountDownLatch.await()方法等待,直到计数器变为0,才开始执行
1. 思路:
a) 建立A B C三个线程,空跑模拟线程运行。
b) 在父进程中通过start()启动各子线程。
c) 利用上述两种方案完成任务。
2. 代码:
TestThread.java
- public class TestThread {
- public static void main(String[] args){
- Thread A=new Thread(new Runnable() {
- @Override
- public void run() {
- int i=0;
- while(i<18){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("A OK");
- }
- });
- Thread B=new Thread(new Runnable() {
- @Override
- public void run() {
- int i=0;
- while(i<10){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("B OK");
- }
- });
- Thread C=new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- A.join();
- B.join();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- int i=0;
- while(i<6){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("C OK");
- }
- });
- A.start();
- B.start();
- C.start();
- }
- }
TestThread2.java
- import java.util.concurrent.CountDownLatch;
- public class TestThread2 {
- public static void main(String[] args){
- CountDownLatch count=new CountDownLatch(2);
- new Thread(new Runnable() {
- @Override
- public void run() {
- int i=0;
- while(i<18){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("A OK");
- count.countDown();
- }
- }).start();
- new Thread(new Runnable() {
- @Override
- public void run() {
- int i=0;
- while(i<10){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("B OK");
- count.countDown();
- }
- }).start();
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- count.await();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- int i=0;
- while(i<6){
- try {
- Thread.sleep(1000);
- }catch (Exception e){
- e.printStackTrace();
- }
- i++;
- }
- System.out.println("C OK");
- }
- }).start();
- }
- }