多线程之同步锁买票-复习篇

package com.lyon.demo.test.mayi;

public class Demo2 {

    public static void main(String[] args) {
        ThreadTrain2 th = new ThreadTrain2();
        Thread thread = new Thread(th);
        Thread thread1 = new Thread(th);
        Thread thread2 = new Thread(th);
        thread.start();
        thread1.start();
        thread2.start();
    }
}


/**
 * 功能描述:(多线程之买火车票案例-使用多线程同步代码解决线程安全问题)
 */
class  ThreadTrain2 implements Runnable{

    private int count = 100;
    // 自定义多线程同步锁
    private Object mutex = new Object();

    @Override
    public void run() {
        //同步锁放在这个位置,只能有一个线程执行
        //synchronized (mutex){
          while (count > 0) {
            try {
                    Thread.sleep(100);
            } catch (InterruptedException e) {
                    e.printStackTrace();
            }
            sale();
        }
    }

    public void sale() {
        synchronized (mutex){
            //同步锁,串行化执行的时候,一定要做对应的逻辑判断
            if(count > 0){
                try {
                    //一旦加锁,sleep睡眠也不会释放锁
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //锁具体资源
                System.out.println("窗口"+Thread.currentThread().getName()+"买了票"+count--);
            }
        }
    }
}
上一篇:表格元素


下一篇:线程