JAVA中的多线程——练习
- /*
- * 需求:
- * 银行有一个金库
- * 有两个储户分别存300元,每次存100,存3次
- * 该程序是否有安全问题,有的话如何解决
- *
- * 问题:
- * 哪些代码是多线程运行代码
- * 明确共享数据
- * 明确多线程运行代码中哪些语句是操作共享数据的
- * */
- /**
- * synchronized可以修饰函数,
- * */
- //class Bank {
- // private int sum;
- //
- // public void add(int n) {
- // sum = sum + n;
- // System.out.println("sum=" + sum);
- // }
- //}
- //
- //class Cus implements Runnable {
- // private Bank bank = new Bank();
- //
- // public void run() {
- // for (int x = 0; x < 3; x++)
- // bank.add(100);
- // }
- //}
- //
- //public class ThreadTest2{
- // public static void main(String args[]){
- // Cus cus=new Cus();
- // Thread thread=new Thread(cus);
- // Thread thread2=new Thread(cus);
- // thread.start();
- // thread2.start();
- // }
- //}
- class Bank {
- private int sum;
- //Object object=new Object();
- public synchronized void add(int n) {
- //synchronized (object) {
- sum = sum + n;
- try {
- Thread.sleep(2000);
- } catch (Exception e) {
- // TODO: handle exception
- }
- System.out.println(Thread.currentThread().getName()+"sum=" + sum);
- //}
- }
- }
- class Cus implements Runnable {
- private Bank bank = new Bank();
- public void run() {
- for (int x = 0; x < 3; x++)
- bank.add(100);
- }
- }
- public class ThreadTest2{
- public static void main(String args[]){
- Cus cus=new Cus();
- Thread thread=new Thread(cus);
- Thread thread2=new Thread(cus);
- thread.start();
- thread2.start();
- }
- }