上一篇博客 Android-Java-同步方法-synchronized,中讲解了普通方法加入synchronized修饰符,此synchronized的同步锁是this,还介绍方法的封装性,这篇博客就不讲方法的封装性了
先看一个 静态方法加入修饰符synchronized(案例)
packageandroid.java.thread12;/*** 售票业务*/
classBooking {/*** 模拟票的总算 10张票*/
private static int ticket = 10;/*** 加入了同步修饰符的方法synchronized,
* 不管CPU如何疯狂的切换执行,
* 只要同步方法里面的代码没有执行完,
* 就不准其他线程进来执行
* 这样就保证了多线程操作共享数据的安全性*/
public static synchronized void actionTicket() { //synchronized同步操作共享数据的代码//synchronized (BookingRunnable.class) {
if (ticket > 0) {//让线程在这里停一下,会更加容易复现线程的安全问题,就算不加这行代码,安全问题依然有
try{
Thread.sleep(200);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("名称:" + Thread.currentThread().getName() + "窗口卖出第" + ticket + "张票");
ticket--;
}//}
}
}/*** 售票任务*/
class BookingRunnable implementsRunnable {
@Overridepublic voidrun() {while (true) {
Booking.actionTicket();
}
}
}/*** 售票案例*/
public classBookingTest {public static voidmain(String[] args) {/*** 定义Runnable实现类Booking,此实现类Booking不是线程,此实现类Booking给四个Thread去执行的*/Runnable booking= newBookingRunnable();//实例化线程对象
Thread thread1 = new Thread(booking); //此实现类Booking给Thread去执行的
Thread thread2 = new Thread(booking); //此实现类Booking给Thread去执行的
Thread thread3 = new Thread(booking); //此实现类Booking给Thread去执行的
Thread thread4 = new Thread(booking); //此实现类Booking给Thread去执行的//开启启动线程
thread1.start(); //启动第Thread-0窗口 执行卖票任务
thread2.start(); //启动第Thread-1窗口 执行卖票任务
thread3.start(); //启动第Thread-2窗口 执行卖票任务
thread4.start(); //启动第Thread-3窗口 执行卖票任务
}
}
执行结果:
静态方法加入synchronized修饰符后,同步静态方法的🔒锁机制--> 锁🔒是当前类名.class
伪代码:>>>>> 静态方法同步的锁🔒是 == 当前类名.class 其实 (当前类名.class)就是字节码文件对象
public static synchronized(锁🔒是 当前类名.class) voidactionTicket() {//.....
}
真实代码:
public static synchronized void actionTicket() { //synchronized同步操作共享数据的代码//synchronized (BookingRunnable.class) {
if (ticket > 0) {//让线程在这里停一下,会更加容易复现线程的安全问题,就算不加这行代码,安全问题依然有
try{
Thread.sleep(200);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("名称:" + Thread.currentThread().getName() + "窗口卖出第" + ticket + "张票");
ticket--;
}//}
}
字节码文件对象 的描述 就是对类的类描述>>>Class
字节码文件对象,内存图:
public synchronized void 方法名(){} , 这种方式的同步锁🔒是 this,当前对象,是对象创建后才会有的 b = new 对象();,b也属于当前对象
public synchronized static void 方法名{},这种方式的同步锁🔒是以上图的(字节码文件对象),当前类的(字节码文件对象),当类加载进内存,就会产生(字节码文件对象);