Java線程同步賣票問題解決方案(synchronized)

關(guān)鍵知識(shí)點(diǎn):synchronized、Runnable

synchronized:

1、使用同步代碼塊進(jìn)行賣票:

public class TicketsCodeBlock implements Runnable { 
    private int count = 100; //總票數(shù)目 

    public static void main(String[] args) { 
        TicketsCodeBlock tickets = new TicketsCodeBlock(); 
        Thread t1 = new Thread(tickets); 
        Thread t2 = new Thread(tickets); 
        Thread t3 = new Thread(tickets); 
        t1.start(); 
        t2.start(); 
        t3.start(); 
     } 
    public void run() { 
        for (int i = 0; i < 10; i++) {
            synchronized (this) { // 同步代碼塊 
                if (count > 0) {
                      try { 
                        Thread.sleep(500); // 500ms 
                      } catch (Exception e){ 
                         e.printStackTrace(); 
                      } 
                      Thread t = Thread.currentThread();
                      System.out.println(t.getName() + " 剩余票的數(shù)目: " + (count--)); 
                  }
             }
         } 
    }
}

2、使用同步方法進(jìn)行賣票:
public class TicketsMethod implements Runnable {
private int count = 100; //總票數(shù)目

public static void main(String[] args) { 
    TicketsMethod tickets = new TicketsMethod(); 
    Thread t1 = new Thread(tickets); 
    Thread t2 = new Thread(tickets); 
    Thread t3 = new Thread(tickets); 
    t1.start(); 
    t2.start(); 
    t3.start(); 
 } 
public void run() { 
    for (int i = 0; i < 10; i++) {
        sale();
    }

}
// 使用同步方法進(jìn)行賣票
public synchronized void sale() {
if (count > 0) {
try {
Thread.sleep(500); // 500ms
} catch (Exception e){
e.printStackTrace();
}
Thread t = Thread.currentThread();
System.out.println(t.getName() + " 剩余票的數(shù)目: " + (count--));
}
}
}
}
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。 首先講...
    李欣陽閱讀 2,600評(píng)論 1 15
  • Java多線程學(xué)習(xí) [-] 一擴(kuò)展javalangThread類 二實(shí)現(xiàn)javalangRunnable接口 三T...
    影馳閱讀 3,111評(píng)論 1 18
  • synchronized是Java中的關(guān)鍵字,是一種同步鎖。它修飾的對象有以下幾種: 修飾一個(gè)代碼塊,被修飾的代碼...
    明教de教主閱讀 713評(píng)論 0 2
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,740評(píng)論 18 399
  • 剛來平順,一路上低矮的山坡,青翠的樹木以及一望無際的平原和遙遙走不到盡頭的公路給這個(gè)陌生的縣城增添了一絲神秘的氣氛...
    ZhaOvZhaO閱讀 341評(píng)論 0 0

友情鏈接更多精彩內(nèi)容