悲观锁:一上来就加锁,每次只能一个线程进来,访问完毕后再解锁。

乐观锁:一上来不上锁,认为是没有问题的,大家一起跑,等出现线程安全时才开始控制。

  

public class Test1 {
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        Runnable target = new MyRunnable();
        for (int i = 1; i <= 100; i++) {
            new Thread(target).start();
        }
    }

    static class MyRunnable implements Runnable {
        private int count = 0;
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
               
                System.out.println(Thread.currentThread().getName() + " " + (++count));//悲观锁。
               
            }
        }
    }
    static class MyRunnable implements Runnable {
        private AtomicInteger count = new AtomicInteger(0);
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {

                
                System.out.println(Thread.currentThread().getName() + " " + count.incrementAndGet());//乐观锁
            }
        }
    }
}

案例:发礼物

1000份礼物。小明和小红分发,算出每人发多少礼物,当礼物小于10份,停止发放。

public class test {
    public static void main(String[] args) throws InterruptedException {
        // 创建100个礼品
        List<String> gift = new ArrayList<>();
        String[] names = {"口红", "包包", "鲜花", "项链", "手表"};
        Random r = new Random();

        for (int i = 0; i < 1000; i++) {
            gift.add(names[r.nextInt(names.length)] + (i + 1));
        }

        System.out.println("礼品列表: " + gift);

        // 定义线程类,创建线程对象。接收gift名单并分发礼物。
        SendThread t1 = new SendThread(gift, "小明");
        t1.start();
        SendThread t2 = new SendThread(gift, "小红");
        t2.start();

        t1.join();//等待上面代码完成,最后统计个数
        t2.join();

        System.out.println( "小明送了"+t1.getCount());
        System.out.println("小红送了"+t2.getCount());


    }
}
public class SendThread extends Thread {
    private List<String> gift;
    private int count = 0;

    public SendThread(List<String> gift, String name) {
        super(name);
        this.gift = gift;
    }


    @Override
    public void run() {
        Random r = new Random();
        while (true) {
            synchronized (gift) {//不使用this锁,而是使用gift锁,因为在调用时候,SendThread用了两次,不唯一
                if (gift.size() < 10) {
                    break;
                }
                // 随机移除一个礼物
                String rs = gift.remove(r.nextInt(gift.size()));
                System.out.println(Thread.currentThread().getName() + " 发送礼物: " + rs);
                count++;
            }
        }
    }

    public void setCount(int count) {
        this.count = count;
    }


    public int getCount() {
        return count;
    }
}