买票问题


/**
 * 买票问题
 */
public class ThreadTrain1 implements Runnable {
    private int count = 10;
    private static Object o = new Object();
    @Override
    public void run() {
        while (count>0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sale();
        }
    }

    private void sale() {
        // 前提 多线程进行使用、多个线程只能拿到一把锁。
        // 保证只能让一个线程 在执行 缺点效率降低
        synchronized (o){
            if (count>0){
                System.out.println(Thread.currentThread().getName()+",出售第"+(10-count+1)+"张票");
                count--;
            }
        }
    }
    public static void main(String[] args){
        ThreadTrain1 train1 = new ThreadTrain1();
        Thread t1 = new Thread(train1,"1号窗口");
        Thread t2 = new Thread(train1,"2号窗口");
        t1.start();
        t2.start();
    }
}

/**
 * 多个线程想要同步,必须用同一把锁
 */
public class ThreadTrain1 implements Runnable {
    private int count = 10;
    private static Object o = new Object();
    public boolean flag = true;
    @Override
    public void run() {
        if (flag){
            synchronized (this){
                while (count>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count>0){
                        System.out.println(Thread.currentThread().getName()+",出售第"+(10-count+1)+"张票");
                        count--;
                    }
                }
            }
        } else {
            sale();
        }
    }

    private synchronized void sale() { //非静态同步函数用的是this锁
        while (count>0){
            if (count>0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+",出售第"+(10-count+1)+"张票");
                count--;
            }
        }
    }
    public static void main(String[] args) throws InterruptedException{
        ThreadTrain1 train1 = new ThreadTrain1();
        Thread t1 = new Thread(train1,"1号窗口");
        Thread t2 = new Thread(train1,"2号窗口");
        t1.start();
        Thread.sleep(40);
        train1.flag = false;
        t2.start();
    }
}
posted @ 2019-08-31 15:51  fly_bk  阅读(227)  评论(0编辑  收藏  举报