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

  • 相关阅读:
    sql sever 的两种写法
    多站点IIS用户安全权限设置图解教程
    phpmyadmin“无法在发生错误时创建会话,请检查 PHP 或网站服务器日志,并正确配置 PHP 安装。”报错解决办法
    天下无难事只怕有心人
    apache配置上传目录禁止运行php的方法
    C语言|博客作业03
    C语言|博客作业07
    C语言|博客作业05
    2019秋季第一周作业
    C语言|博客作业06
  • 原文地址:https://www.cnblogs.com/RunForLove/p/4158615.html
Copyright © 2011-2022 走看看