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();
        }
    }
  • 相关阅读:
    Hive sql
    Hive严格模式
    Hive 分区表和分桶表
    hive
    Hive内部表与外部表区别详解
    HDFS
    Hadoop
    MySQL数据库优化
    Mysql常用存储引擎介绍
    Day12-Mysql服务日志类型及增量恢复命令
  • 原文地址:https://www.cnblogs.com/onway/p/3438960.html
Copyright © 2011-2022 走看看