静态同步函数
什么是静态同步函数?
方法上加上static关键字,使用synchronized 关键字修饰 或者使用类.class文件。
静态的同步函数使用的锁是 该函数所属字节码文件对象
可以用 getClass方法获取,也可以用当前 类名.class 表示。
public static void sale() { //前面有static修饰了 静态的不需要被实例化 不可以用this
synchronized (ThreadTrain3.class) { //当前类的clas
if (trainCount > 0) {
System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - trainCount + 1) + "张票");
trainCount--;
}
}
}
总结:
synchronized 修饰方法使用锁是当前this锁。
synchronized 修饰静态方法使用锁是当前类的字节码文件
可以证明:(两个线程在执行 拿到的锁不一样)
package com.toov5.threadSecurity;
class Thread009 implements Runnable {
private static int trainCount = 1000;
private Object oj = new Object();
public static boolean flag = true;
public void run() {
if (flag) {
while (trainCount>0) {
synchronized (this) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
if (trainCount > 0) {
System.out.println("true");
System.out.println(Thread.currentThread().getName() + "," + "出售第" + (100 - trainCount + 1) + "票"+flag);
trainCount--;
}
}
}
} else {
while (trainCount > 0) {
synchronized (this) {
System.out.println("fasle");
sale();
}
}
}
}
public static synchronized void sale() {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
if (trainCount > 0) {
System.out.println(Thread.currentThread().getName() + "," + "出售第" + (100 - trainCount + 1) + "票"+flag);
trainCount--;
}
}
}
public class Test009 {
public static void main(String[] args) throws InterruptedException {
Thread009 threadTrain = new Thread009();
Thread t1 = new Thread(threadTrain, "窗口1");
Thread t2 = new Thread(threadTrain, "窗口2");
t1.start();
Thread.sleep(30);
threadTrain.flag = false;
t2.start(); //t2线程走下面的那段代码
}
}
肯定不能同步的
一个用的当前字节码文件 一个用的this