方法执行线程数控制方法(一)

        在多线程编程模式下,经常会遇到一个方法调用不能有太多线程同时执行,这样做的好处是服务器运行稳定,不易宕机。那么有什么方式可以做到控制方法同时执行的线程数不会太多压垮服务器呢?其实也是那么几种经典的解决方式,只是在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");	
	}	

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值