• java常见面试题3:线程间通信


    写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z

    打印顺序为12A34B56C78D……5152Z。要求用线程间的通信。

     

    代码清单:

    class Printer {
        private int index = 1;
      /* 打印数字*/
        public synchronized void print(int i) {
            while (index % 3 == 0) {
                try {
                    wait();
                } catch (Exception e) {
                }
            }
            System.out.print(i);
            index++;
            notifyAll();
        }
    
      /* 打印字母*/
        public synchronized void print(char c) {
            while (index % 3 != 0) {
                try {
                    wait();
                } catch (Exception e) {
                }
            }
            System.out.print(c);
            index++;
            notifyAll();
        }
    }
    
    class NOPrinter implements Runnable {
        private Printer p;
    
        NOPrinter(Printer p) {
            this.p = p;
        }
    
        public void run() {
            for (int i = 1; i <= 52; i++) {
                p.print(i);
            }
        }
    }
    
    class LetterPrinter implements Runnable {
        private Printer p;
    
        LetterPrinter(Printer p) {
            this.p = p;
        }
    
        public void run() {
            for (char c = 'A'; c <= 'Z'; c++) {
                p.print(c);
            }
        }
    }
    
    public class ResourceDemo {
        public static void main(String[] args) {
            Printer p = new Printer();
            NOPrinter np = new NOPrinter(p);
            LetterPrinter lp = new LetterPrinter(p);
    
            Thread th1 = new Thread(np);
            Thread th2 = new Thread(lp);
            th1.start();
            th2.start();
        }
    }
  • 相关阅读:
    CSS(22)CSS的长度单位
    CSS(21)CSS Grid网格布局
    CSS(20)CSS3 弹性盒子(Flex Box)
    CSS(19)CSS3 多列
    CSS(18)CSS3 过渡与动画
    CSS(17)CSS 2D、3D 转换
    CSS(16)CSS3 渐变(Gradients)
    CSS(15)CSS媒体查询Media Queries
    CSS(14)CSS 伪元素
    CSS(13)CSS 伪类(Pseudo-classes)
  • 原文地址:https://www.cnblogs.com/onway/p/3438960.html
Copyright © 2020-2023  润新知