Object lock = new Object();
for(int i = 0;i < threads.length; i++){
threads[i] =
new Thread(new Runnable(){
@Override
public void run() {
for(int k = 0; k < 100000; k++){
synchronized (lock){
count2++;
}
}
}
});
}
start = System.currentTimeMillis();
for(Thread t : threads) t.start();
for(Thread t : threads) t.join();
end = System.currentTimeMillis();
System.out.println("synchronized使用Runnable匿名類: " + count2 + " time: " + (end-start));
//----------------------------------------------------------
Object lockb = new Object();
for(int i = 0;i < threads.length; i++){
threads[i] =
new Thread(()->{
/*@Override
public void run() {*/
for(int k = 0; k < 100000; k++){
synchronized (lockb){
count4++;
}
}
});
}
start = System.currentTimeMillis();
for(Thread t : threads) t.start();
for(Thread t : threads) t.join();
end = System.currentTimeMillis();
System.out.println("synchronized匿名類: " + count4 + " time: " + (end-start));
uj5u.com熱心網友回復:
運行結果分別是synchronized使用Runnable匿名類: 100000000 time: 6502
synchronized匿名類: 100000000 time: 3889
為啥差別這么大?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/92077.html
標籤:Java SE
