一个线程不安全的例子

package com.example.demoClient.lg;

/**
 * @author Dongguabai
 * @date 2018/11/10 16:53
 */
public class Demo3 {

    private int value = 1;

    public static void main(String[] args) {
        Demo3 demo3 = new Demo3();
        new Thread(() -> {
            while (true) {
                System.out.println("用户" + Thread.currentThread().getName() + "买了第" + demo3.increamentAndGet() + "张票");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "张三").start();
        new Thread(() -> {
            while (true) {
                System.out.println("用户" + Thread.currentThread().getName() + "买了第" + demo3.increamentAndGet() + "张票");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "王五").start();
        new Thread(() -> {
            while (true) {
                System.out.println("用户" + Thread.currentThread().getName() + "买了第" + demo3.increamentAndGet() + "张票");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "李四").start();

    }

    //synchronized
    public int increamentAndGet() {
        return value++;
    }
}

 

你可能感兴趣的:(一个线程不安全的例子)