Java-在同步函数中使用锁

/*
 * 同步函数用的是哪一个锁呢?
 * 函数需要被对象调用。那么函数都有一个所属对象引用。就是this
 * 所以同步函数使用的锁是this
 *
 * 通过该程序进行验证
 *
 * 使用两个线程来买票
 *  一个线程在同步代码块中
 * 一个线程在同步函数中
 * 都在执行买票动作
 *
 * 如果同步函数被静态修饰后,使用的锁是什么呢?
 * 通过验证,发现不是this。因为静态方法中也不可以定义this
 *
 * 静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象,类名.class。该对象的类型是class
 * 静态的同步方法,使用的锁是该方法所在类的字节码文件对象。类名.class
 */

class Ticket1 implements Runnable{
    private static int ticket1 = 100;
//    Object obj1 = new Object();
    boolean flag1 = true;

    
    public void run() {
        if(flag1) {
            while(true) {
                synchronized(Ticket1.class) {
                    if(ticket1>0) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+"--code--"+ticket1--);
                    }
                }
        }
        }else {
            while(true) {
                show();
            }
        }
            
    }
    public static synchronized void show() {//this
            if(ticket1>0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"--show--"+ticket1--);
            }
        }
    }

    

public class ThisLockDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Ticket1 t = new Ticket1();
        
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        
        t1.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        t.flag1 = false;
        t2.start();

    }

}

猜你喜欢

转载自blog.csdn.net/Lydia233/article/details/102319815