import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo {
ExecutorService threadExecutor = Executors.newFixedThreadPool(2);
@Test
public void test1() throws InterruptedException {
// 1 req
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
Demo demo = new Demo();
demo.execute(1);
}
}).start();
// 2 req
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
Demo demo = new Demo();
demo.execute(1);
}
}).start();
// for (int i = 0; i < 10; i++) {
// Demo demo = new Demo();
// demo.execute(1);
// }
}
public void execute(Integer type) throws InterruptedException {
switch (type) {
case 1:
CountDownLatch countDownLatch = new CountDownLatch(3);
threadExecutor.execute(() -> {
try {
// do something A
System.out.println(Thread.currentThread() + ":::::do something A,type=" + type);
} catch (Exception e) {
System.out.println("e=" + e);
} finally {
countDownLatch.countDown();
}
});
threadExecutor.execute(() -> {
try {
// do something B
System.out.println(Thread.currentThread() + ":::::do something B,type=" + type);
} catch (Exception e) {
System.out.println("e=" + e);
} finally {
countDownLatch.countDown();
}
});
threadExecutor.execute(() -> {
try {
// do something C
System.out.println(Thread.currentThread() + ":::::do something C,type=" + type);
} catch (Exception e) {
System.out.println("e=" + e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
break; //可选
case 2:
//语句
countDownLatch = new CountDownLatch(1);
threadExecutor.execute(() -> {
try {
// do something D
System.out.println(Thread.currentThread() + ":::::do something D,type=" + type);
} catch (Exception e) {
System.out.println("e=" + e);
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
break; //可选
default: //可选
System.out.println(1);
//语句
break;
}
System.out.println(Thread.currentThread() + "::::: main do something E,type=" + type);
}
}
如上面的代码块,假如两次或多次请求(如下图),代码块是否可以保证顺序性?两次或多次请求过来是否会按照代码顺序重新 new CountDownLatch(3);如果会那么上述代码块中的CountDownLatch是否发挥作用?