java线程处理业务

package test;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.lucene.index.IndexWriter;

import com.index.bdo.IndexBusinessContextInterface;
import com.index.config.model.IndexSequenceInfo;
import com.index.enums.SeqRecStatusType;
import com.index.lucene.IndexModifier;
import com.index.worker.impl.CommonIndexWorker;

public class TestThread {
	public static final int MAXIMUM_POOL_SIZE = 300;

	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		Thread1 thread = new Thread1();
		LinkedBlockingQueue queue = new LinkedBlockingQueue(MAXIMUM_POOL_SIZE);
		thread.setQueue(queue);
		//启动它
		new Thread(thread).start();
		
		//这里放入要处理的东西
		Object o = new Object();
		queue.put(o);
	}

}
class Thread1 implements Runnable{
	LinkedBlockingQueue queue;
	private boolean interrupted = false;//是否被停止
	public void setInterrupted(boolean interrupted) {
		this.interrupted = interrupted;
	}

	public void setQueue(LinkedBlockingQueue queue) {
		this.queue = queue;
	}

	public void run() {
		try {
			//------------------------------------------
			Object businessObject = null;
			int size  = -1;
			while (!interrupted) {
				long startTime = new Date().getTime();
	    		try {
	    			if(size!=-1 && size-1<=0){//说明没有下一个了
	    				Thread.sleep(1500);//休息
	    			}
	    			//记录下size
	    			size = this.queue.size();
	    			//取出队列里面的业务对象来处理
	    			businessObject = this.queue.take();
	    			try {
						//执行业务处理逻辑
	    				//XXXXXXXXXXXXx
	    				//XXXXXXXXXXXXXXXXXXXx
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						//做些必要的处理
		    		}
		    		long endTime = new Date().getTime();
		    		System.out.println("[线程队列]花费了" + (endTime - startTime) + " 毫秒来处理业务!");
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		}
			}//end while
			//------------------------------------------
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//最后
		}//end finally
	}
}

你可能感兴趣的:(java线程)