线程池的使用

1、通过创建一个拥有固定数目的线程的线程池
2、每次启动指定数目线程去执行任务,把线程的创建、维护交给线程池来管理
3、将多线程任务设置到定时任务中,观察线程执行情况

==============
如果不采用线程池,在我机器上运行大概35秒钟,程序就挂了!!!

package threads;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 线程池测试
*
* @author liuwei
*/
public class TestThreadPool extends TimerTask
{

private List<TestBean> initData = new ArrayList<TestBean>();

private ExecutorService services = null;

private final int threadNum = 1000;

private final int cycleNum = 80;

// 初始化数据及线程池
public TestThreadPool()
{
int n = threadNum * 2 + 3;
int c = 1;
for (int i = 1; i <= n; i++)
{
initData.add(new TestBean(cycleNum, String.valueOf(c)));
c++;
}

// 查看系统cpu个数
// int cpuNum = Runtime.getRuntime().availableProcessors();
// System.out.println("cpu number : " + cpuNum);
services = Executors.newFixedThreadPool(threadNum);
}

/**
* 需要多线程执行的方法
*
* @param obj
*/
public void toPrint(TestBean obj)
{
if (null == obj)
{
return;
}

int n = obj.getN();
for (int i = 0; i < n; i++)
{
try
{
Thread.sleep(200);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("============" + Thread.currentThread().getName() + ", str : " + obj.getStr());
}
} // toPrint

// 执行线程方法的线程类
private class TestRun implements Runnable
{
private TestBean obj;

public TestRun(TestBean obj)
{
this.obj = obj;
}

public void run()
{
toPrint(obj);
}
} // TestRun


public void run()
{
int size = initData.size();
int count = (size + threadNum - 1) / threadNum;
System.out.println("count: " + count);
for (int i = 0; i < count; i++)
{
System.out.println("====================" + i);
for (int j = 0; j < threadNum; j++)
{
int index = i * threadNum + j;
// System.out.println("index: "+index);
if (index >= size)
{
break;
}
final TestBean obj = initData.get(i * threadNum + j);
// System.out.println(obj.getN());
// new Thread(new TestRun(obj)).start();
services.execute(new TestRun(obj));

}

} // end-for-initData

} // run


/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Timer timer = new Timer();
TestThreadPool tt = new TestThreadPool();
// 启动后立即执行,每隔15秒钟在执行一次
timer.schedule(tt, 0, 15 * 1000);

// 关闭线程池
// tt.services.shutdown();
}

} // TestThreadPool


class TestBean
{
private int n;
private String str;

public TestBean(int n, String str)
{
this.n = n;
this.str = str;
}

public int getN()
{
return n;
}

public void setN(int n)
{
this.n = n;
}

public String getStr()
{
return str;
}

public void setStr(String str)
{
this.str = str;
}
} // TestBean
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值