同步函数--卖票

class Ticket2 implements Runnable {

    private int tick = 100;
    public void run() {  //不能将整个run()方法加锁,因为并不是整个函数都需要同步。
        while (true) {
            show();
        }
    }

    public synchronized void show(){
        if (tick > 0) {
            try {Thread.sleep(10);} catch (Exception e) {}
            System.out.println(Thread.currentThread().getName() + "sale: " + tick--);
        }
    }
}

public class ThisLockDemo {

    public static void main(String[] args) throws InterruptedException {

        Ticket2 t = new Ticket2(); // t本身不是线程,没有实现Thread对象

        Thread t1 = new Thread(t); // 创建线程
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

你可能感兴趣的:(同步函数--卖票)