package com.test.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
public class Executor {
private static Logger logger = Logger.getLogger(Executor.class);
private ExecutorService putRequestToListPool = null;
private ExecutorService sentRequestPool = null;
private static List requestList = new ArrayList();
private static List timeToSleep;
private static Random random = new Random();
private static int putRequestPoolSize = 1;
private static int sendRequestPoolSize = 4;
public static void main(String[] args) {
timeToSleep = new ArrayList();
timeToSleep.add(4000);
Executor exec = new Executor();
exec.putRequestToListPool = Executors.newFixedThreadPool(putRequestPoolSize);
exec.sentRequestPool = Executors.newFixedThreadPool(sendRequestPoolSize);
exec.initRequestList();
exec.sendRequest();
}
public void initRequestList(){
System.out.println("start initRequestList");
for (int i = 0; i < putRequestPoolSize; i++) {
putRequestToListPool.execute(new Runnable() {
public void run() {
int num = 0;
while (num<300) {
if(requestList.size()<=10){
num = num + 1;
requestList.add("test"+num);
}
}
}
});
}
}
public void sendRequest(){
System.out.println("start sendRequest");
for (int i = 0; i < sendRequestPoolSize; i++) {
final int threadID = i;
sentRequestPool.execute(new Runnable() {
public void run() {
while(true) {
System.out.println(threadID);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//sendRequest(threadID);
}
}
});
}
}
private void sendRequest(int threadID){
if(threadID==1)
try {
Thread.sleep(1000*60*20);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendRequestToSleep(threadID);
}
private String getFitstRequestFromList(){
String firstRequest = "";
synchronized(requestList){
if(requestList.size()==0){
System.out.println("发送完毕");
System.exit(0);
}else{
firstRequest = requestList.get(0);
requestList.remove(0);
}
}
return firstRequest;
}
private void sendRequestToSleep(int threadID){
synchronized(timeToSleep){
int nextSleepTime = random.nextInt(100);
try {
int sleep = timeToSleep.get(0);
//System.out.println("ThreadID="+threadID+"-send="+getFitstRequestFromList()+"-sleep="+sleep+" TIME="+System.currentTimeMillis()+"-nextSleepTime="+nextSleepTime+"-requestList="+requestList.size());
System.out.println("ThreadID="+threadID+"-send="+getFitstRequestFromList());
Thread.sleep(sleep);
timeToSleep.set(0, nextSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}