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 时间?)。
本文通过实例演示了如何使用Java模拟高并发场景,并探讨了利用AtomicInteger和synchronized关键字配合wait、notify方法来控制并发数量的方法。通过设置条件变量和合理运用线程阻塞,有效地解决了高并发带来的问题。
1938

被折叠的 条评论
为什么被折叠?



