多线程练习题

1. 创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D

// 同步方法 synchronized修饰函数
// 思考:如何保证主线程最后的结束而非阻塞?
//注意: notifyall()的位置在当前线程wait()的前面
//java print不换行 println自动换行

// 思考:如何保证主线程最后的结束而非阻塞?
//注意: notifyall()的位置在当前线程wait()的前面
public class examination_16_1 {
   
    //  这个类相当于共享变量
    //同步监视器类,提供线程安全的方法
    class printResult{
   
        private int number=1;
        private char character='A';
        //提供两个synchronized方法
        //  synchronized方法  ;notifyall()的位置在当前线程wait()的前面
        public synchronized void printnumber(){
            System.out.print(number+""+(number+1));
            number+=2;
            notifyAll();
                try {
                    //  大于52之后不再等待;
                    if (number <= 52) wait();
                    //使用while(number <= 52) wait();会一直循环,后面notify也跳不出来
                } catch (Exception e) {
                    System.out.println(e.toString());
                }

        }
        public synchronized void printcharacter(){
            System.out.println(character+" ");
            character+=1;
            notifyAll();
            try {
                //  大于Z之后不再等待;如果不加最后不会结束!!阻塞了
                if(character<='Z') wait();
            }catch (Exception e){
                System.out.println(e.toString());
            }
        }
    }
    class Number implements Runnable{
   
        private printResult printresult;
        public Number(printResult p){
            this.printresult=p;
        }
        private int i=0;
        public void run(){
            for(;i<26;i++) {
                //调用同步监视器中的方法
                printresult.printnumber();
               //System.out.println(Thread.currentThread().getName()+"  "+i);
            }
        }
    }
    
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值