zoukankan      html  css  js  c++  java
  • 多线程经典编程题 实践篇

    题目一:写两个线程,一个线程打印1~52,另一个线程打印字母A~Z。打印顺序为12A34B56C........5152Z。要求用线程间的通信。package test;
    import java.lang.Thread;
    class Printer{
        private int index = 1;
        public synchronized void print(int n){
            while(index%3==0){
                try{
                    wait();
    /*在其他线程调用此对象的notify方法钱,导致当前线程等待*/
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
            System.out.print(index);
            index++;
            notifyAll();
        }
        public synchronized void print(char c){
            while(index%3!=0){
                try{
                    wait();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            System.out.print(c);
            System.out.print(index);
            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 CharPrinter extends Thread{
        private Printer p;
        public CharPrinter(Printer p){
            this.p=p;
        }
        public void run(){
            for(char c='A';c<='Z';c++)
                p.print(c);
        }
    }
    public class MyThread {
        public static void main(String args[]){
            Printer p = new Printer();
            Thread t1 = new NumberPrinter(p);
            Thread t2 = new CharPrinter(p);
            t1.start();
            t2.start();
        }
    }

  • 相关阅读:
    微信小程序开发---各代码文件简介
    LeetCode71. 简化路径
    LeetCode70. 爬楼梯
    LeetCode69. x 的平方根
    LeetCode68. 文本左右对齐
    LeetCode剑指 Offer 09. 用两个栈实现队列
    LeetCode67. 二进制求和
    LeetCode66. 加一
    LeetCode65. 有效数字
    LeetCode64. 最小路径和
  • 原文地址:https://www.cnblogs.com/RunForLove/p/4158615.html
Copyright © 2011-2022 走看看