Java線程:線程的同步(同步塊)

字號(hào):

對(duì)于同步,除了同步方法外,還可以使用同步代碼塊,有時(shí)候同步代碼塊會(huì)帶來比同步方法更好的效果。
    追其同步的根本的目的,是控制競爭資源的正確的訪問,因此只要在訪問競爭資源的時(shí)候保證同一時(shí)刻只能一個(gè)線程訪問即可,因此Java引入了同步代碼快的策略,以提高性能。
    在上個(gè)例子的基礎(chǔ)上,對(duì)oper方法做了改動(dòng),由同步方法改為同步代碼塊模式,程序的執(zhí)行邏輯并沒有問題。
    /**
    * Java線程:線程的同步-同步代碼塊
    *
    */
    public class Test {
    public static void main(String[] args) {
    User u = new User("張三", 100);
    MyThread t1 = new MyThread("線程A", u, 20);
    MyThread t2 = new MyThread("線程B", u, -60);
    MyThread t3 = new MyThread("線程C", u, -80);
    MyThread t4 = new MyThread("線程D", u, -30);
    MyThread t5 = new MyThread("線程E", u, 32);
    MyThread t6 = 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;
    }