证明创建runnable实例和普通类时间一样长
生活随笔
收集整理的這篇文章主要介紹了
证明创建runnable实例和普通类时间一样长
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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計數減一
}
}
}
轉載于:https://www.cnblogs.com/fengdaren/p/9765922.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的证明创建runnable实例和普通类时间一样长的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一晚上梦到好几次蛇是怎么回事
- 下一篇: mysql异机备份