形象解释java synchronized 为啥不能使用if只能使用while

代码背景

现在你正在玩植物大战僵尸,有生产者—向日葵,一次生产25阳光,消费者—豌豆射手卷心菜投手仙人掌,都消耗100阳光。

wait和notify实现

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
/**
 * 生产者消费者模式:使用Object.wait() / notify()方法实现
 */
public class ProducerConsumer {
    private static final int CAPACITY = 500;

    public static void main(String args[]){
        int sun = 0;

        Thread producer1 = new Producer("向日葵1", sun , CAPACITY);
        Thread producer1 = new Producer("向日葵2", sun , CAPACITY);
        Thread consumer1 = new Consumer("豌豆射手", sun , CAPACITY);
        Thread consumer2 = new Consumer("卷心菜投手", sun , CAPACITY);
        Thread consumer3 = new Consumer("仙人掌射手", sun , CAPACITY);

        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
        consumer3.start();
    }

    /**
     * 生产者
     */
    public static class Producer extends Thread{
        private int sun ;
        String name;
        int maxSize;
        int i = 0;

        public Producer(String name, int sun, int maxSize){
            super(name);
            this.name = name;
            this.sun= sun;
            this.maxSize = maxSize;
        }

        @Override
        public void run(){
            while(true){
                synchronized(sun){
                    if(sun >= 500){
                        try {
                            System.out .println("阳光达到上限, [" + name + "] 产生的阳光 " + "需要被拿来种下植物");
                            sun.wait();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }x
                    System.out.println("[" + name + "] 生产了25阳光");
                    sun += 25;
                    sun.notifyAll();

                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    /**
     * 消费者
     */
    public static class Consumer extends Thread{
        private int sun;
        String name;
        int maxSize;

        public Consumer(String name, int sun, int maxSize){
            super(name);
            this.name = name;
            this.sun= sun;
            this.maxSize = maxSize;
        }

        @Override
        public void run(){
            while(true){
                synchronized(sun){
                    if(sun - 100 <= 0){
                        try {
                            System.out.println("没有阳光了, 栽种[" + name + "] 急需向日葵生产阳光");
                            queue.wait();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    sun -= 100;
                    System.out.println("种下一颗[" + name + "] 消耗100阳光" + x);
                    sun .notifyAll();

                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

上述代码一运行,啪!报错!,为啥,原来synchronized 锁对 Integer基本类型的包装类没有效果,采用一个Wrapper包装一下

修改后

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * 生产者消费者模式:使用Object.wait() / notify()方法实现
 */
class Wrapper{
    public Integer sum = 0;
}

public class Main {
    private static final int CAPACITY = 300;

    public static void main(String args[]){
        Wrapper sun = new Wrapper();
        sun.sum = 0;

        Thread producer1 = new Producer("向日葵1", sun , CAPACITY);
        Thread producer2 = new Producer("向日葵2", sun , CAPACITY);
        Thread consumer1 = new Consumer("豌豆射手", sun , CAPACITY);
        Thread consumer2 = new Consumer("卷心菜投手", sun , CAPACITY);
        Thread consumer3 = new Consumer("仙人掌射手", sun , CAPACITY);

        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
        consumer3.start();
    }

    /**
     * 生产者
     */
    public static class Producer extends Thread{
        private Wrapper sun ;
        String name;
        int maxSize;

        public Producer(String name, Wrapper sun, int maxSize){
            super(name);
            this.name = name;
            this.sun= sun;
            this.maxSize = maxSize;
        }

        @Override
        public void run(){
            while(true){
                synchronized(sun){
                    if(sun.sum >= maxSize){
                        try {
                            System.out .println("阳光达到上限, [" + name + "] 产生的阳光 " + "需要被拿来种下植物");
                            sun.wait();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    sun.sum += 25;
                    System.out.println("[" + name + "] 生产了25阳光,现在共有" + sun.sum + "阳光");
                    sun.notifyAll();

                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    /**
     * 消费者
     */
    public static class Consumer extends Thread{
        private Wrapper sun;
        String name;
        int maxSize;

        public Consumer(String name, Wrapper sun, int maxSize){
            super(name);
            this.name = name;
            this.sun= sun;
            this.maxSize = maxSize;
        }

        @Override
        public void run(){
            while(true){
                synchronized(sun){
                    if(sun.sum - 100 < 0){
                        try {
                            System.out.println("没有阳光了, 栽种[" + name + "] 急需向日葵生产阳光");
                            sun.wait();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    sun.sum -= 100;
                    System.out.println("种下一颗[" + name + "] 消耗100阳光,现在共有" + sun.sum + "阳光");
                    sun .notifyAll();

                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

运行效果:
在这里插入图片描述
我去,怎么有负数!!!

synchronized 不能使用if只能使用while

在上面这个例子中,仙人掌射手所属的线程首先被唤醒了,通过while循环和if操作顺利消耗了所有阳光,并进入了wait状态。但是,现在卷心菜投手也被唤醒了,他没经过if判断,直接把阳光-100,然后执行下一次时才发现阳光居然是负数,马上进入wait状态,但是这时候已经迟了。所以得改成while让他先进行判断再操作。

修改代码

if(sun.sum - 100 < 0) 改为 while(sun.sum - 100 < 0)
if(sun.sum >= maxSize) 改为 while(sun.sum >= maxSize)

在这里插入图片描述
非常的完美!!!

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个示例,演示了如何在Java中实现无锁并发代码,而不使用Atomic、synchronized和Lock。 ```java public class NoLockConcurrencyExample { private static volatile int counter = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new IncrementTask()); Thread t2 = new Thread(new IncrementTask()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Counter value: " + counter); } static class IncrementTask implements Runnable { @Override public void run() { for (int i = 0; i < 10000; i++) { incrementCounter(); } } } private static void incrementCounter() { int oldValue; int newValue; do { oldValue = counter; newValue = oldValue + 1; } while (!compareAndSet(oldValue, newValue)); } private static boolean compareAndSet(int expect, int update) { if (counter == expect) { counter = update; return true; } return false; } } ``` 在这个示例中,我们使用一个volatile修饰的counter变量来存储计数器的值。volatile关键字确保了多线程之间的可见性,即一个线程修改了counter的值,其他线程能够立即看到最新的值。 在IncrementTask任务中,我们使用一个自定义的incrementCounter方法来递增计数器的值。该方法使用了一个自旋的compare-and-set循环,不断尝试修改counter的值直到成功。compareAndSet方法通过比较当前counter的值和期望的值,如果相等则更新为新值。 这种无锁的实现方式利用了volatile关键字的可见性和CAS(Compare-and-Swap)操作的原子性,避免了使用显式锁,从而实现了无锁并发。 需要注意的是,这个示例只是一个简单的演示,并不适用于所有场景。在实际开发中,需要仔细评估使用无锁并发的适用性和性能,并根据具体需求进行选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值