同步块是一段代码,可用于对方法的任何特定资源执行同步。 同步块用于锁定任何共享资源的对象,并且同步块的范围小于同步方法。
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中文网其他相关文章!