對於同步,除了同步方法外,還可以使用同步代碼塊,有時候同步代碼塊會帶來比同步方法更好的效果。
追其同步的根本的目的,是控制競爭資源的正確的訪問,因此只要在訪問競爭資源的時候保證同一時刻只能一個線程訪問即可,因此Java引入了同步代碼快的策略,以提高性能。
在上個例子的基礎上,對oper方法做了改動,由同步方法改為同步代碼塊模式,程序的執行邏輯並沒有問題。
package cn.thread; /** * 線程同步方法 * * @author 林計欽 * @version 1.0 2013-7-24 上午10:12:47 */ public class ThreadSynchronizedCode { public static void main(String[] args) { ThreadSynchronizedCode t = new ThreadSynchronizedCode(); User u = t.new User("張三", 100); MyThread t1 = t.new MyThread("線程A", u, 20); MyThread t2 = t.new MyThread("線程B", u, -60); MyThread t3 = t.new MyThread("線程C", u, -80); MyThread t4 = t.new MyThread("線程D", u, -30); MyThread t5 = t.new MyThread("線程E", u, 32); MyThread t6 = t.new MyThread("線程F", u, 21); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); } class MyThread extends Thread { private User u; /**存款金額*/ private int y = 0; MyThread(String name, User u, int y) { super(name); this.u = u; this.y = y; } public void run() { u.oper(y); } } class User { /** 賬號 */ private String code; /** 余額 */ private int cash; User(String code, int cash) { this.code = code; this.cash = cash; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } /** * 存款 * * @param x 欲存款金額 * */ public void oper(int x) { try { Thread.sleep(10L); synchronized (this) { this.cash += x; System.out.println("線程" + Thread.currentThread().getName() + "運行結束,增加“" + x + "”,當前用戶賬戶余額為:" + cash); } Thread.sleep(10L); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString() { return "User{" + "code='" + code + '\'' + ", cash=" + cash + '}'; } } }
線程線程B運行結束,增加“-60”,當前用戶賬戶余額為:40 線程線程A運行結束,增加“20”,當前用戶賬戶余額為:60 線程線程C運行結束,增加“-80”,當前用戶賬戶余額為:-20 線程線程D運行結束,增加“-30”,當前用戶賬戶余額為:-50 線程線程F運行結束,增加“21”,當前用戶賬戶余額為:-29 線程線程E運行結束,增加“32”,當前用戶賬戶余額為:3