内容描述:
在多线程中,有两个任务A与B,多线程执行任务A完成后再继续执行任务B,想到的两种方法一种线程间通信,使用条件变量方式,第二种就是使用CountDownLatch。
条件变量
主要使用的条件变量,判断是否任务A已经做完,然后再执行任务B
public class Main {
public static boolean[] flag = new boolean[3];
public static boolean judge(boolean[] f) {
for (int i = 0; i < f.length; i++) {
if (!f[i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
for (int i = 0; i < flag.length; i++) {
flag[i] = false;
}
new Thread(new Runnable() {
public void run() {
while (true) {
if (!flag[0]) {
System.out.println("T1: work A");
flag[0] = true;
}
if (judge(flag)) {
System.out.println("T1: work B");
break;
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
if (!flag[1]) {
System.out.println("T2: work A");
flag[1] = true;
}
if (judge(flag)) {
System.out.println("T2: work B");
break;
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
if (!flag[2]) {
System.out.println("T3: work A");
flag[2] = true;
}
if (judge(flag)) {
System.out.println("T3: work B");
break;
}
}
}
}).start();
}
}
运行结果:
使用CountDownLatch
我们也可以使用CountDownLatch,然后通过CountDown()与await()方法进行线程运行与等待。
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException{
CountDownLatch countDownLatch = new CountDownLatch(3);
new Thread(new Runnable() {
public void run() {
System.out.println("aWork: A ");
countDownLatch.countDown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("aWork: B");
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("bWork: A ");
countDownLatch.countDown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("bWork: B");
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("cWork: A ");
countDownLatch.countDown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("cWork: B");
}
}).start();
}
}