天天看點

弱智題: 三個線程輪流列印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++,釋放鎖之後,結束

繼續閱讀