1
回答
利用Condition控制多线程同步输出ABC未达到预期
终于搞明白,存储TCO原来是这样算的>>>   

我计划依次输出ABC,10次,但是结果却发生异常,有可能C输出后还输出C,一时没想清楚,大家帮忙看看,代码如下:

package com.mc.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * XXXX
 *
 * @author Alistar
 * @date 2017/8/13
 */
public class ConditionABC {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(5);
        Demo demo = new Demo();
        CountDownLatch latch = new CountDownLatch(30);

        for (int i = 0; i < 10; i++) {
            service.execute(() -> {
                demo.sayA();
                try {
                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            service.execute(() -> {
                demo.sayB();
                try {
                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            service.execute(() -> {
                demo.sayC();
                try {
                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        latch.await();

        System.out.print("SUCCESS");
        service.shutdown();

    }
}

class Demo {
    private volatile int flag = 1;

    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    public void sayA() {
        lock.lock();
        try {
            if (flag != 1) {
                conditionA.await();
            }

            System.out.print("A"+flag);
            flag = 2;
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sayB() {
        lock.lock();
        try {
            if (flag != 2) {
                conditionB.await();
            }

            System.out.print("B" + flag);
            flag = 3;
            conditionC.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void sayC() {
        lock.lock();
        try {
            if (flag != 3) {
                conditionC.await();
            }

            System.out.print("C" + flag);

            flag = 1;
            conditionA.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}

 

<无标签>
举报
CodingNew
发帖于2个月前 1回/52阅
顶部