JAva同期コードブロックと同期関数

847 ワード

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);
		}
		
	}
	
}