线程--同步函数被static修饰锁是类名.class

package java09_06;

/**
* static 没有this
*同步函数被static修饰:
* static方法随类的加载而加载,这是不一定有该类对象。但是一定有一个该类的字节码文件。
* 这个对象简单的表示方法是:类名.class
*
*/

public class ThreadTestNO2 {

public static void main(String[] args) throws InterruptedException {
    TicketTWO test = new  TicketTWO();

    Thread t1 = new Thread(test,"张三");
    Thread t2 = new Thread(test,"李四");
    t1.start();
    Thread.sleep(10); //让主线程把执行资格和执行权让出来 ,
    test.flag = false;
    t2.start();

}

}
class TicketTWO implements Runnable{
private static int ticket = 100;
//定义一个boolean标记
boolean flag = true;
@Override
public void run() {
// TODO Auto-generated method stub
if(flag){
while (true) {
synchronized (TicketTWO.class) {
// synchronized (this) {
if(ticket>0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+”–run—剩余的票数是:”+(–ticket));
}
}
}
}else
while (true)
Sale();//同步函数

}

public static synchronized void Sale() {
    if(ticket>0){
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"--Sale--剩余的票数是:"+(--ticket));
    }
}

}

猜你喜欢

转载自blog.csdn.net/weixin_39816332/article/details/77875414