同步區塊是一段程式碼,可用來對方法的任何特定資源執行同步。 同步區塊用於鎖定任何共用資源的對象,且同步區塊的範圍小於同步方法。
synchronized(object) { // block of code }
此處,物件是對正在同步的物件的參考。同步區塊確保僅在目前執行緒成功進入物件的監視器後才會呼叫物件的成員方法。
class TicketCounter { int availableSeats = 2; void bookTicket(String name, int numberOfSeats) { if((availableSeats >= numberOfSeats) && (numberOfSeats > 0)) { System.out.println(name+" : "+ numberOfSeats + " Seats Booking Success"); availableSeats -= numberOfSeats; } else { System.out.println(name +" : Seats Not Available"); } } } class TicketBookingThread extends Thread { TicketCounter tc; String name; int seats; TicketBookingThread(TicketCounter tc, String name, int seats) { this.tc = tc; this.name = name; this.seats = seats; } public void run() { <strong> synchronized(tc) { // synchronized block </strong> tc.bookTicket(name, seats); } } } public class SynchronizedBlockTest { public static void main(String[] args) { TicketCounter tc = new TicketCounter(); TicketBookingThread t1 = new TicketBookingThread(tc, "Adithya", 2); TicketBookingThread t2 = new TicketBookingThread(tc, "Jai", 2); t1.start(); t2.start(); } }
Adithya : 2 Seats Booking Success Jai : Seats Not Available
以上是在Java中,我們什麼時候可以使用同步區塊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!