在多线程编程模式下,经常会遇到一个方法调用不能有太多线程同时执行,这样做的好处是服务器运行稳定,不易宕机。那么有什么方式可以做到控制方法同时执行的线程数不会太多压垮服务器呢?其实也是那么几种经典的解决方式,只是在JDK不同的版本下实现有所差异罢了。
方法一:使用队列,将执行方法的线程挂起入队列。后台增加一个扫描线程,批量将队列内的线程唤醒执行。上代码。
客户端模拟线程执行代码: ThreadClient.java
/**
*
*/
package com.yq.thread;
/**
* @author yangqiang
*
*/
public class ThreadClient extends Thread{
/**
* @param args
*/
public static void main(String[] args) {
//模拟客户端500次请求
int total = 500;
Thread[] threads = new Thread[total];
for(int i = 0; i < total; i++){
threads[i] = new ThreadClient();
threads[i].setName("t" + i);
threads[i].start();
}
}
@Override
public void run() {
//调用服务端处理方法
Service.getInstance().service();
}
}
扫描类:Scan.java
package com.yq.thread;
import java.util.concurrent.LinkedBlockingQueue;
public class Scan extends Thread{
/** 一次允许执行的线程数 */
private int size;
/** 存储挂起线程的队列 */
private LinkedBlockingQueue<Thread> queue;
public Scan(int size, LinkedBlockingQueue<Thread> queue) {
super();
this.size = size;
this.queue = queue;
}
@Override
public void run() {
while(true){
for(int i = 0; i < size; i++){
try {
Thread thread = queue.take();
thread.resume();
} catch (InterruptedException e) {
System.out.println("scan error");
}
}
}
}
}
服务器代码:Service.java
/**
*
*/
package com.yq.thread;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
/**
* @author yangqiang
*
*/
public class Service {
static LinkedBlockingQueue<Thread> queue = new LinkedBlockingQueue<Thread>();
static Scan scan;
static final int size = 5;
static Service self = new Service();
long start = System.currentTimeMillis();
static{
scan = new Scan(size, queue);
scan.setDaemon(true);
scan.start();
}
public static Service getInstance(){
return self;
}
public void service(){
queue.add(Thread.currentThread());
Thread.currentThread().suspend();
long end = System.currentTimeMillis();
System.out.println("invoke by " + Thread.currentThread().getName() + " " + (end-start)/1000 + " s");
}
}