经典笔试题:多线程实现按顺序打印十遍ABC

//使用三个线程按照顺序打印ABC,打印十遍。这是一个比较经典的笔试题,实现方式有多种,主要是考察
//线程的协调调用,下面使用线程的 wait和notifyAll 通讯方式来实现

public class ThreadPrint {

    int flag =1;

    int num=10;

    public void printA() throws InterruptedException {
        synchronized (this){
            while (num>0){

                if(flag==1){
                    System.out.println("num="+num);
                    System.out.println("A");
                    flag=2;
                    num--;
                    notifyAll();
                }else {
                    wait();
                }
            }
        }
    }

    public void printB() throws InterruptedException {
        synchronized (this){
            while (num>=0){
                if(flag==2){
                    System.out.println("B");
                    flag=3;
                    notifyAll();
                }else {
                    wait();
                }
            }
        }
    }

    public void printC() throws InterruptedException {
        synchronized (this){
            while (num>=0){
                if(flag==3){
                    System.out.println("C");
                    flag=1;
                    notifyAll();
                    if (num==0){
                        num--;
                    }
                }else {
                    wait();
                }
            }

        }
    }


    public static void main(String[] args) {
        final  ThreadPrint threadPrint  = new ThreadPrint();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    threadPrint.printA();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    threadPrint.printB();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    threadPrint.printC();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章