Loading

多线程笔试题记录

线程题1

设置三个线程并行

t1打印a
t2打印b
t3打印c

输出abc abc abc abc

/**
*
* 设计三个线程并发执行
* t1 打印 a
* t2 打印 b
* t3 打印 c
*
* 输出 abc abc abc abc
*
*/
public class LockTest9 {
    public static void main(String[] args) {
        WaitNofity waitNofity = new WaitNofity();

    //线程t1
        new Thread(() ->{
            try {
                waitNofity.print("a",1,2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();

    //线程t2
        new Thread(() ->{
            try {
                waitNofity.print("b",2,3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();

    //线程t3
        new Thread(() ->{
            try {
                waitNofity.print("c",3,1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t3").start();

    }



    static class WaitNofity{
        //执行标志
        int flag = 1;

        /**
         * @Param content 输出内容
         * @Param waitFlag 本次执行标志
         * @Param nextFlag 下次执行标志
         **/
        public void print(String content,int waitFlag,int nextFlag) throws InterruptedException {
            for (int i = 0; i < 4; i++){
                synchronized (this){
                    while (flag != waitFlag){
                        this.wait();//阻塞
                    }
                    System.out.print(content);
                    if(waitFlag == 3){
                        System.out.print(" ");
                    }
                    flag = nextFlag;
                    this.notifyAll();//唤醒全部
                }

            }
        }
    }

}

执行结果:

image-20210726212054511

posted @ 2021-07-26 21:25  yescctv6  阅读(80)  评论(0编辑  收藏  举报