溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java線程同步-synchronized

發(fā)布時(shí)間:2020-06-22 15:55:12 來源:網(wǎng)絡(luò) 閱讀:458 作者:_追隨我心 欄目:軟件技術(shù)
  1. synchronized:同步(鎖),可以修飾代碼塊和方法,被修飾的代碼塊和方法一旦被某個(gè)線程訪問,則直接鎖住,其他的線程將無法訪問
  2. 非靜態(tài)方法的同步鎖對(duì)象是this
    靜態(tài)方法的鎖同步對(duì)象是當(dāng)前類的字節(jié)碼對(duì)象

模擬火車站售票案例

同步代碼塊:
public class Ticket implements Runnable {

int tickets = 100;//總票數(shù)
Object obj = new Object(); //鎖對(duì)象

@Override
public void run() {
    //賣票
    while (true) {
        synchronized (obj) {
            if (tickets > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "賣出了第" + (tickets--) + "張票");
            }
        }
    }
}

}

同步方法
public class Ticket implements Runnable {

int tickets = 100;//總票數(shù)
Object obj = new Object(); //鎖對(duì)象

@Override
public void run() {
    //賣票
    while (true) {
        method();
    }
}

public synchronized void method(){
    if (tickets > 0) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "賣出了第" + (tickets--) + "張票");
    }
}

}

測(cè)試類
public class TicketTest {
public static void main(String args[]){

    Ticket t = new Ticket();

    Thread t1 = new Thread(t);
    Thread t2 = new Thread(t);
    Thread t3 = new Thread(t);

    t1.setName("窗口1");
    t2.setName("窗口2");
    t3.setName("窗口3");

    t1.start();
    t2.start();
    t3.start();
}

}

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI