多线程_03_安全

什么时候会出现安全问题:
当多个线程,对同一个共享数据执行操作的时候。

案例:

火车票的购买:

package com.mr.thread;

/**
 * 线程安全方面
 *
 *      火车票购买
 */
public class Demo3 implements Runnable{

    private static int num = 200;

    @Override
    public void run() {
        try {
            for (int i = 0; i < 2000; i++) {
                synchronized (Demo3.class){//synchronized锁
                    if(num > 0){//当车票大于0 ,抢票
                        num--;//t1 35-1 t2 :35-1
                        System.out.println("非常开心抢票成功!剩余"+num+ "张"+"---"+Thread.currentThread().getName());
                        //车票订单
                        Thread.sleep(5);//睡5ms
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class TestDemo3{

    public static void main(String[] args) {

        //某程
        Demo3 d1 = new Demo3();
        Thread t1 = new Thread(d1);
        t1.start();

        //某猪
        Demo3 d2 = new Demo3();
        Thread t2 = new Thread(d2);
        t2.start();

        //某龙
        Demo3 d3 = new Demo3();
        Thread t3 = new Thread(d3);
        t3.start();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37392489/article/details/86504619