java线程池

5 篇文章 0 订阅
package com.dt.test;


import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;






public class Test implements Runnable{


public static void main(String[] args) {



Test test = new Test();
// test.t1(200000); //573毫秒 采用线程池
//   test.t2(200000); //72483毫秒 灭有采用线程池

Test mt=new Test();
Thread t1=new Thread(mt,"t1");
Thread t2=new Thread(mt,"t2");
Thread t3=new Thread(mt,"t3");
Thread t4=new Thread(mt,"t4");
Thread t5=new Thread(mt,"t5");
Thread t6=new Thread(mt,"t6");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();







}


public void t1(int count){

long startTime = System.currentTimeMillis();
final List<Integer> l = new LinkedList<Integer>();

ThreadPoolExecutor tp  =
new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count));

final Random random = new Random();
for (int i = 0; i < count; i++) {
tp.execute( new Runnable() {
public void run() {

l.add(random.nextInt());

}
});

}

tp.shutdown();
try {

tp.awaitTermination(1, TimeUnit.DAYS);

} catch (InterruptedException e) {
e.printStackTrace();
}



System.out.println(System.currentTimeMillis()-startTime);
System.out.println(l.size());


}


public void t2(int count){

long  startTime = System.currentTimeMillis();

final List<Integer> l = new LinkedList<Integer>();

final Random random = new Random();

for (int i = 0; i < count; i++) {
Thread  thread = new Thread(){

public void run() {
l.add(random.nextInt());
}

};

thread.start();
try {
thread.join();

} catch (InterruptedException e) {
e.printStackTrace();
}

}

System.out.println(System.currentTimeMillis()-startTime);
System.out.println(l.size());


}




@Override
public void run() {

synchronized (this) { //一次只能有一个线程进入
System.out.println(Thread.currentThread().getName());
}


}













}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值