启动三个线程,分别打印A B C,现在写一个程序 循环打印ABCABCABC....

刚才看到一个博客(http://wangxinchun.iteye.com/blog/1859250)里写了一道面试题:

 

启动三个线程,分别打印A B C,现在写一个程序 循环打印ABCABCABC....

 

原文中有很多实现方法。

我感觉如果可以用Java5以后的Semaphore实现的话会比较简单,于是写了一个实现:

package org.devside.study.synchronous;

import java.util.concurrent.Semaphore;

/**
 * User: matianyi
 * Date: 13-5-4
 * Time: 下午8:58
 */
public class ThreadSync {
    static class ConditionThread extends Thread {
        ConditionThread(Semaphore preCond, Semaphore postCond, String text) {
            this.preCond = preCond;
            this.postCond = postCond;
            this.text = text;
        }

        private Semaphore preCond;
        private Semaphore postCond;
        private String text;

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    preCond.acquire();
                    System.out.print(text);
                    postCond.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphoreA = new Semaphore(0);
        Semaphore semaphoreB = new Semaphore(0);
        Semaphore semaphoreC = new Semaphore(1);

        Thread threadA = new ConditionThread(semaphoreC, semaphoreA, "A");
        Thread threadB = new ConditionThread(semaphoreA, semaphoreB, "B");
        Thread threadC = new ConditionThread(semaphoreB, semaphoreC, "C");

        threadA.start();
        threadB.start();
        threadC.start();

        threadA.join();
        threadB.join();
        threadC.join();
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值