A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© abckids 中级黑马   /  2016-7-8 23:31  /  2776 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

5黑马币
模拟两个人向银行存钱,每次存300,两个人总共存十次

最佳答案

查看完整内容

package com.itheima.day19; public class Test01 { public static void main(String[] args) { /* * 模拟两个人向银行存钱,每次存300,两个人总共存十次 */ MyRunnable mr = new MyRunnable(); new Thread(mr,"MCC").start(); new Thread(mr,"BZ").start(); } } class MyRunnable implements Runnable { private int count = 1; @Override public void run() { while(true) { try { Thread.sleep ...

3 个回复

正序浏览
66666666666666
回复 使用道具 举报
楼上的非常好.给赞,上课的实例,
回复 使用道具 举报
package com.itheima.day19;

public class Test01 {
        public static void main(String[] args) {
                /*
                 * 模拟两个人向银行存钱,每次存300,两个人总共存十次
                 */
                MyRunnable mr = new MyRunnable();
                new Thread(mr,"MCC").start();
                new Thread(mr,"BZ").start();
        }
}


class MyRunnable implements Runnable {
        private int count = 1;
        @Override
        public void run() {
                while(true) {
                        try {
                                Thread.sleep(20);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        synchronized (this) {
                                if (count <= 10) {
                                        //存钱
                                        System.out.println("第" + count++ + "次,存300块钱的人是:" + Thread.currentThread().getName());
                                }else {
                                        return;
                                }
                        }
                }
        }
       
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马