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

© 122125241 中级黑马   /  2015-7-7 22:18  /  499 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test {
  2.         public static void main(String[] args) {
  3.                 User u = new User("张三", 100);
  4.                 MyThread t1 = new MyThread("线程A", u, 20);
  5.                 MyThread t2 = new MyThread("线程B", u, -60);
  6.                 MyThread t3 = new MyThread("线程C", u, -80);
  7.                 MyThread t4 = new MyThread("线程D", u, -30);
  8.                 MyThread t5 = new MyThread("线程E", u, 32);
  9.                 MyThread t6 = new MyThread("线程F", u, 21);

  10.                 t1.start();
  11.                 t2.start();
  12.                 t3.start();
  13.                 t4.start();
  14.                 t5.start();
  15.                 t6.start();
  16.         }
  17. }

  18. class MyThread extends Thread {
  19.         private User u;
  20.         private int y = 0;

  21.         MyThread(String name, User u, int y) {
  22.                 super(name);
  23.                 this.u = u;
  24.                 this.y = y;
  25.         }

  26.         public void run() {
  27.                 u.oper(y);
  28.         }
  29. }

  30. class User {
  31.         private String code;
  32.         private int cash;

  33.         User(String code, int cash) {
  34.                 this.code = code;
  35.                 this.cash = cash;
  36.         }

  37.         public String getCode() {
  38.                 return code;
  39.         }

  40.         public void setCode(String code) {
  41.                 this.code = code;
  42.         }

  43.         /**
  44.          * 业务方法
  45.          * @param x 添加x万元
  46.          */
  47.         public synchronized void oper(int x) {
  48.                 try {
  49.                         Thread.sleep(10L);
  50.                         this.cash += x;
  51.                         System.out.println(Thread.currentThread().getName() + "运行结束,增加“" + x + "”,当前用户账户余额为:" + cash);
  52.                         Thread.sleep(10L);
  53.                 } catch (InterruptedException e) {
  54.                         e.printStackTrace();
  55.                 }
  56.         }

  57.         @Override
  58.         public String toString() {
  59.                 return "User{" +
  60.                                 "code='" + code + '\'' +
  61.                                 ", cash=" + cash +
  62.                                 '}';
  63.         }
  64. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马