- package inter;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.concurrent.locks.Condition;
- public class ThreadTest3 {
- private static Lock lock = new ReentrantLock();
- private static Condition subThreadCondition = lock.newCondition();
- private static boolean bBhouldSubThread = false;
- public static void main(String[] args) {
- ExecutorService threadPool = Executors.newFixedThreadPool(2);
- threadPool.execute(new Runnable() {
- public void run() {
- for (int i = 0; i < 5; i++) {
- lock.lock();
- try {
- if (!bBhouldSubThread){//不应该应该执行子线程
- subThreadCondition.await();
- System.out.println("我开始执行了"+bBhouldSubThread);
- }
- for (int j = 0; j < 2; j++) {
- System.out.println("我开始执行了2");
- System.out.println(Thread.currentThread().getName()
- + ",j=" + j);
- }
- bBhouldSubThread = false;
- subThreadCondition.signal();
- } catch (Exception e) {
- } finally {
- lock.unlock();
- }
- }
- }
- });
- threadPool.shutdown();//在完成已提交的任务后关闭服务,不再接受新任务
- for (int i = 0; i < 5; i++) {
- System.out.println("我啊啊啊啊啊啊啊");
- lock.lock();
- try {
- if (bBhouldSubThread){//应该执行子线程
- System.out.println("我啊啊啊啊啊啊啊3"+bBhouldSubThread);
- subThreadCondition.await();
- }
- for (int j = 0; j < 10; j++) {
- System.out.println(Thread.currentThread().getName() + ",i="
- + j);
- }
- bBhouldSubThread = true;
- subThreadCondition.signal();
- } catch (Exception e) {
- } finally {
- System.out.println("我啊啊啊啊啊啊啊2");
- lock.unlock();
- }
- }
- }
- }
复制代码 这是主线程和子线程轮番打印数字的程序,我想问一下,是不是subThreadCondition.await();这句之后停在哪儿,然后调用subThreadCondition.signal();之后就在subThreadCondition.await();这句之后继续执行。例如停在了红色的这一句System.out.println("我啊啊啊啊啊啊啊3"+bBhouldSubThread);,那么执行了signal之后会继续执行下面的for循环?还有个问题,只有一个condition, subThreadCondition.await();这句被调用后,那么到底谁等待啊,这个是怎么控制的,可以说下原理吗?谢谢更多0
|