package thread.sync;
/*
* 需求:储户,两个,每个都到银行存钱每次存100,,共存三次。
*/
public class BankDemo {
public static void main(String[] args) {
Cus c = new Cus();
System.out.println(c);
//静态同步函数用此,该函数的字节码文件对象
System.out.println(c.getClass());
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Bank {
private int sum;
Object obj = new Object();
//同步函数,它的锁是this
public synchronized void add(int num){
//同步代码块解决线程安全隐患
// synchronized (obj){
sum+=num;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum="+sum+"--");
// }
}
}
class Cus implements Runnable{
private Bank b = new Bank();
@Override
public void run() {
for(int i = 0; i<3; i++){
b.add(100);
}
}
}