弱智题: 三个线程轮流打印ABC

import java.util.concurrent.locks.ReentrantLock;

public class PrintABC {
    public static final ReentrantLock lock = new ReentrantLock();
    public static char cnt = 'A';
    public static int times = 0;

    public static void main(String[] args) {
        new Thread(new Ap()).start();
        new Thread(new Bp()).start();
        new Thread(new Cp()).start();
    }


    static class Ap implements Runnable{

        @Override
        public void run() {
            while(true){
                go();
            }

        }
        private void go(){
            try{
                lock.lock();
                if(cnt == 'A' && times < 30){
                    System.out.print(Thread.currentThread().getName()
                            +"---print---A---");
                    cnt = 'B';
                    times++;
                    System.out.println(times);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }

        }
    }
    static class Bp implements Runnable{

        @Override
        public void run() {
            while(true){
                go();
            }

        }
        private void go(){
            try{
                lock.lock();
                if(cnt == 'B' && times < 30){
                    System.out.print(Thread.currentThread().getName()
                            +"---print---B---");
                    cnt = 'C';
                    times++;
                    System.out.println(times);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
    static class Cp implements Runnable{

        @Override
        public void run() {
            while(true){
                go();
            }

        }
        private void go(){
            try{
                lock.lock();
                if(cnt == 'C' && times < 30){
                    System.out.print(Thread.currentThread().getName()
                            +"---print---C---");
                    cnt = 'A';
                    times++;
                    System.out.println(times);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}


要点:
1 用new 三个thread实现,每一个thread的构造器里new各自的类,外部测试类,要有3个静态变量,一把final的lock,一个static的cnt 代表当前字符,一个static count 代表运行次数
2 每个类都是静态的,实现Runnable接口,重写run方法,run方法里写死while,循环内部运行私有方法
3 私有方法里要用try catch 包裹,并且finally最后要释放锁,方法内部先去看cnt是否是与当前线程匹配的变量,循环次数是不是到达上限,if条件达到之后,打印当前线程name 输出cnt,之后改cnt的值,然后count++,释放锁之后,结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值