java线程池

来源:互联网 发布:赛维网络加班严重吗 编辑:程序博客网 时间:2024/06/05 18:42
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