同步块是一段代码,可用于对方法的任何特定资源执行同步。 同步块用于锁定任何共享资源的对象,并且同步块的范围小于同步方法。
语法
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() {
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中,我们什么时候可以使用同步块?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!