• 多线程笔试题记录


    线程题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

  • 相关阅读:
    webstrom破解的问题
    redis高级应用(1)
    linux之软链接、硬链接
    爬虫之scrapy、scrapy-redis
    爬虫之xpath、selenuim
    爬虫之Beautifulsoup模块
    爬虫之Reuqests模块使用
    测试项目配置
    Cleary基础
    Redis基础
  • 原文地址:https://www.cnblogs.com/doagain/p/15063400.html
Copyright © 2020-2023  润新知