同步块是一段代码,可用于对方法的任何特定资源执行同步。 同步块用于锁定任何共享资源的对象,并且同步块的范围小于同步方法。
此处,对象是对正在同步的对象的引用。同步块确保仅在当前线程成功进入对象的监视器后才会调用对象的成员方法。
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() { synchronized(tc) { // synchronized block 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中文网其它相关文章!
已抢65167个
抢已抢28757个
抢已抢15665个
抢已抢7901个
抢已抢9898个
抢已抢20055个
抢