Java 高并发模拟以及如何解决高并发的一些操作

1. 此文章主要讲述了如何模拟高并发以及如何解决高并发的两种方式

2. 结合 (1)的要点与 wait、notify 的使用,尝试解决高并发的一些问题(下面是代码,bool的作用就是设置阻塞)

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;



    /**

     * Created with IntelliJ IDEA.

     * User: 菜鸟大明

     * Date: 14-10-21

     * Time: 下午4:34

     * To change this template use File | Settings | File Templates.

     */

    public class BingFa implements Runnable{

        final AtomicInteger number = new AtomicInteger();

        volatile boolean bol = false;



        @Override

        public void run() {
            System.out.println("瞬间并发量:" + number.getAndIncrement());
            synchronized (this) {

                try {

                    if(number.intValue() > 20){
                        Thread.sleep((long)(Math.random() * 1000));
                    }

                    if (!bol) {

                        System.out.println(bol);

                        bol = true;

                        Thread.sleep(1000);
                        bol = false;
                        notify();

                    } else {
                        wait();
                        System.out.println(bol);

                        bol = true;

                        Thread.sleep(1000);
                    }

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println("并发数量剩余:" + number.decrementAndGet());

            }



        }



        public static void main(String[] args) {

            ExecutorService pool = Executors. newCachedThreadPool();

            BingFa test = new BingFa();

            for (int i=0;i<30;i++) {

                pool.execute(test);

            }

        }

    }

这里使用 AtomicInteger 记录并发数量。使用 Boolean 作为条件,并配合 wait、notify的使用,若当前并发数量超出一定范围,那么使用sleep方式可以一定程度上阻塞一定数量的并发请求(我们是否可以这样,根据当前不同的并发数量来对 sleep 进行设置,并发数量越高,那就延长 sleep 时间?)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值