Java的内存模型(1)

package com.zhang.thread.rammodel;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zb
 * @version 1.0
 * @name RamModelClass
 * @description java内训模型
 * @date 2018/12/19
 *
 * 在下面的代码中的内存模型将会如下所示
 *
 *            主内存变量    num = 0;
 *
 * thread_01    本地内存(相当于内存变量的一个副本)    num = 0;
 *
 * thread_02    本地内存(相当于内存变量的一个副本)    num = 0;
 *
 * 下面的代码将会得出错误的结果,是因为多线程造成的,我们下面来分析原因
 *
 * 假设在开始:thread_01  线程开始操作共享变量(基于本地内存操作),是的num++,此时num的值为2,但是这个值只是存在
 * 于本地主内存中,在主内存中的num变量的值依然等于1,
 * 在thread_01 线程对num的操作还没有结束的时候thread_02进入了操作num的代码快,此刻他看到的num也是本地内存的num=1,所以会导致错误
 *
 * 同样加入还有一个线程来操作num,他看到的也是主内存中的num的值,即num=1
 *
 *
 *
 */



public class RamModelClass {

    /**
     * 主内存中的共享变量
     */
    private static Integer num = 0;

    public static void main(String[]args){
        //启动多个线程

        MyThraed thread_01 =  new MyThraed("thread_01");
        MyThraed thraed_02 = new MyThraed("thread_02");


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5, 100, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(10));
        //同时启动像个线程
        threadPoolExecutor.execute(thread_01);
        threadPoolExecutor.execute(thread_01);
    }





    static class MyThraed implements  Runnable {


        private String thredName;//线程名字

        public MyThraed(String thredName) {
            this.thredName = thredName;
        }
        @Override
        public void run() {
            //线程操作共享变量(不安全的)
            num++;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "MyThraed{" +
                    "thredName='" + thredName + '\'' +
                    '}';
        }
    }
}

package com.zhang.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 这里将会介绍如何实现原子性的常见手段以及java中的处理当方法
 *
 * 1、通过锁住总线来保证:简而言之就是当一个变量被多个cpu操作的时候,在一个cpu获得对这个变量的操作全之后
 * 系统会锁住cpu和内存的通信,使得其他cpu无法访问内存。(不建议使用这种策略)
 *
 *
 * 2、使用缓存策略
 *
 *
 * java中的策略
 *    1、借助于CAS操作实现(需要考虑通过version来防止ABA问题)
 *    2、借助于锁实现
 *
 *
 * Created by zb on 2018/12/18.
 */
public class CASOperation {
     static int i = 0;
     static  AtomicInteger atomicInteger = new AtomicInteger(0);

    static Counter counter = new Counter();

    public static void main(String[]args)throws Exception{
        //这里使用线程池启动执行100个线程
        //线程池的参数
        /**@param corePoolSize the number of threads to keep in the pool, even
         *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
         * @param maximumPoolSize the maximum number of threads to allow in the
         *        pool
         * @param keepAliveTime when the number of threads is greater than
         *        the core, this is the maximum time that excess idle threads
         *        will wait for new tasks before terminating.
         * @param unit the time unit for the {@code keepAliveTime} argument
         * @param workQueue the queue to use for holding tasks before they are
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(10));
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for(int i = 0;i<100;i++ ) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    counter.safeCount();
                    counter.unSafeCount();
                }
            });
        }

        countDownLatch.await();

        System.out.println("线程安全的计数:"+atomicInteger.get());
        System.out.println("线程不安全的计数:"+atomicInteger.get());
    }





    static  class Counter {

        //线程安全的计数
        public void safeCount() {
            while(true) {
                int  i = atomicInteger.get();
                //注意这个函数的额用法
                /**
                 * @param expect the expected value
                 * @param update the new value
                 * @return {@code true} if successful. False return indicates that
                 * the actual value was not equal to the expected value.
                 */
                boolean falg = atomicInteger.compareAndSet(i,i++);
                //代表更新成功
                if(falg) {
                    break;
                }
            }
        }

        //线程不安全的计数
        public void unSafeCount() {
              i++;  //等价于  i = i+1;
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值