zoukankan      html  css  js  c++  java
  • wait and notifyAll

    package com.karl.multithread;
    
    public class Test {
        public static void main(String[] args) {
            Printer p = new Printer();
            Thread t1 = new NumberPrinter(p);
            Thread t2 = new LetterPrinter(p);
            t1.start();
            t2.start();
        }
    }
    
    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 NumberPrinter extends Thread {
        private Printer p;
        public NumberPrinter(Printer p) {
            this.p = p;
        }
        public void run() {
            for (int i = 1; i <= 52; i++) {
                p.print(i);
            }
        }
    }
    
    class LetterPrinter extends Thread {
        private Printer p;
        public LetterPrinter(Printer p) {
            this.p = p;
        }
        public void run() {
            for (char c = 'A'; c <= 'Z'; c++) {
                p.print(c);
            }
        }
    }

     1 2 A 3 4 B 5 6 C 7 8 D 9 10 E 11 12 F 13 14 G 15 16 H 17 18 I 19 20 J 21 22 K 23 24 L 25 26 M 27 28 N 29 30 O 31 32 P

  • 相关阅读:
    PostMessage
    __stdcall
    C++中L和_T()之区别
    号外:百度开源了它的人工智能技术
    最棒的Unity Github 项目收集(2016)
    OpenGL学习笔记——求值器和NURBS
    unity3d四元数和旋转矩阵
    C# System.Timers.Time
    进程地址空间分布
    子进程与父进程
  • 原文地址:https://www.cnblogs.com/zhonghan/p/2881388.html
Copyright © 2011-2022 走看看