zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    linux 邮件服务器
    Nginx学习之keepalive
    explain 和 desc 详解
    mysql 常用语句
    loop设备及losetup命令
    cryptsetup文件系统加密
    ftp主动与被动模式详解
    大型网站关键技术
    大访问量网站架构设计
    Mysql 的事务隔离级别
  • 原文地址:https://www.cnblogs.com/onway/p/3438960.html
Copyright © 2011-2022 走看看