多線程初探(五)

package com.liujunhua.it02;
/**
 * 同步函數:
 * 同步代碼塊是用來封裝代碼的,而函數也是用來封裝代碼的
 * 那麼函數可以不可以同步呢?
 * 當然是可以的,在函數前面加上synchronized關鍵字就可以了
 */
public class Demo02 {

	public static void main(String[] args){
		
		Cus1 cus1 = new Cus1();
		
		Thread t1 = new Thread(cus1);
		Thread t2 = new Thread(cus1);
		Thread t3 = new Thread(cus1);
		
		t1.start();
		t2.start();
		t3.start();
		
	}
}

class Bank1 {

	private int sum = 0;

	public synchronized void add(int n) {

			sum = sum + n;
			System.out.println("sum=" + sum);
	}

}

class Cus1 implements Runnable {

	private Bank b = new Bank();

	@Override
	public void run() {

		for (int i = 0; i < 3; i++) {
			b.add(100);
		}
	}

}

發佈了71 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章