java Executor实例_Java-Executor实例

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();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值