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();
        }
    }

  • 相关阅读:
    NodeJS优缺点
    移动端触摸相关事件touch、tap、swipe
    vscode使用技巧
    js 字符串转数字
    js 导出Excel
    <!--[if IE 9]> <![endif]-->
    js 异步请求
    关于windows串口处理
    mfc 托盘提示信息添加
    微软的麦克风处理示列代码
  • 原文地址:https://www.cnblogs.com/RunForLove/p/4158615.html
Copyright © 2011-2022 走看看