21.2并发(2)

并发编程第二篇

不正确的访问资源

  • 在Java中,递增不是原子操作

  • 当多线程操作EvenGerator对象时,A线程正在操作第一个++currentEvenValue,此刻又进来一个线程B操作,就产生出现了并发问题。

    public class EvenGenerator extends IntGenerator {
        private int currentEvenValue = 0;
    
        public int next() {
            ++currentEvenValue; // Danger point here!
            ++currentEvenValue;
            return currentEvenValue;
        }
    
        public static void main(String[] args) {
            EvenChecker.test(new EvenGenerator(),10);
        }
    }
    
    public class EvenChecker implements Runnable {
        private IntGenerator generator;
        private final int id;
    
        public EvenChecker(IntGenerator g, int ident) {
            generator = g;
            id = ident;
        }
    
        public void run() {
            while (!generator.isCanceled()) {
                int val = generator.next();
                if (val % 2 != 0) {
                    System.out.println(val + " not even!");
                    generator.cancel(); // Cancels all EvenCheckers
                }
            }
        }
    
        // Test any type of IntGenerator:
        public static void test(IntGenerator gp, int count) {
            ExecutorService exec = Executors.newCachedThreadPool();
            for (int i = 0; i < count; i++)
                exec.execute(new EvenChecker(gp, i));
            exec.shutdown();
        }
    }
    

解决共享资源竞争

  • Java提供关键字synchronized锁形式,当任务要执行被synchronized关键字保护的代码时,需要先请求锁(不可用需等待其他任务释放锁),执行代码,释放锁。

  • JVM负责跟踪对象被加锁的次数,通俗的讲当任务获取到当前对象的锁时(对于其他任务来讲就是给此对象加锁),此对象的加锁次数+1,再操作此对象其他加锁的方法时,再+1(只有首先获得对象的锁才可以持续获取多个锁),最后当任务离开加锁的方法时(释放锁),加锁次数递减,直至为0;对于其他任务来讲就可以获取锁了,依次循环。

  • 锁分类:方法锁(其实也是对象锁),对象锁,类锁(静态方法锁)。

    同步使用场景:

    如果你正在写一个变量,它接下来可能会被其他线程操作,获取你正在操作的变量刚被其他线程操作过,就应该使用同步。并且,读写线程都需要使用相同的监视器(锁)。

    注意事项:

    1.使用并发时,将域设置为private时非常重要的,否则synchronized关键字就不能防止其他任务访问,将会产生冲突。

    public class SynchronizedEvenGenerator extends IntGenerator {
        private int currentEvenValue = 0;
    
        public synchronized int next() {
            ++currentEvenValue;
    //        Thread.yield(); // Cause failure faster
    //        ++currentEvenValue;
            return currentEvenValue;
        }
    
        public static void main(String[] args) {
            EvenChecker.test(new SynchronizedEvenGenerator());
        }
    }
    
  • 使用显示的Lock对象:Lock对象必须显示的创建、锁定和释放,虽然看起来不太优雅,但会更灵活一些。

    public class MutexEvenGenerator extends IntGenerator {
        private int currentEvenValue = 0;
        private Lock lock = new ReentrantLock();
    
        public int next() {
            lock.lock();
            try {
                ++currentEvenValue;
                Thread.yield(); // Cause failure faster
                ++currentEvenValue;
                return currentEvenValue;
            } finally {
                lock.unlock();
            }
        }
    
        public static void main(String[] args) {
            EvenChecker.test(new MutexEvenGenerator());
        }
    }
    
  • ReentrantLock重入锁:允许你尝试获取但最终未获取锁,即使别人获取了锁你也可以去执行其他事情,而不用一直等待。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.解决信号量丢失和假唤醒 public class MyWaitNotify3{ MonitorObject m...
    Q罗阅读 906评论 0 1
  • JUC 原创者:文思,感谢尚硅谷,资料来源于尚硅谷 目录: 1、volatile关键字与内存可见性 2、原子变量与...
    文思li阅读 2,378评论 0 1
  • 在一般性开发中,笔者经常看到很多同学在对待java并发开发模型中只会使用一些基础的方法。比如Volatile,sy...
    张勇_bf29阅读 707评论 0 1
  • Object类位于java.lang包中,java.lang包有最基础的和核心的类,在编译时会自动导入; Obje...
    遇见你的故事阅读 632评论 0 0
  • 并发:当有多个线程在操作时,如果系统只有一个CPU,则它根本不可能真正同时进行一个以上的线程,它只能把CPU运行时...
    zlb阅读 430评论 0 0