import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//证明创建runnable实例和普通类时间一样长, 其实这是自己对线程和任务混淆了
public class Test002 {
private ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
// private ArrayList<String> queue = new ArrayList<String>();
// private CyclicBarrier barrier = new CyclicBarrier(10000000);
private CountDownLatch latch = new CountDownLatch(100000);
ExecutorService es = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
Test002 test001 = new Test002();
long timeStart = System.currentTimeMillis();
test001.begin();
System.out.println("##线程类实例化10000次时间:"+(System.currentTimeMillis()-timeStart));
timeStart = System.currentTimeMillis();
test001.begin2();
System.out.println("##普通类实例化10000次时间:"+(System.currentTimeMillis()-timeStart));
}
public void begin(){
for (int i = 0; i < 10000; i++) {
Runnable001 runnable001 = this.new Runnable001(i);
}
}
public void begin2(){
for (int j = 0; j < 10000; j++) {
Runnable002 Runnable002 = this.new Runnable002(j);
// new Thread(); // 时间主要花在创建线程上,使用runnable接口不占用时间
}
}
private class Runnable001 implements Runnable{
private int value;
public Runnable001(int value) {
this.value = value;
}
public void run() {
try {
// barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
queue.offer(value + "");
latch.countDown();//latch计数减一
}
}
private class Runnable002 {
private int value;
public Runnable002(int value) {
this.value = value;
}
public void run() {
try {
// barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
queue.offer(value + "");
latch.countDown();//latch计数减一
}
}
}