for(int i=0; I & lt; Threads. Length; I++) {
Threads [I]=
New Thread (new Runnable () {
@ Override
Public void the run () {
For (int k=0; K & lt; 100000; K++) {
Synchronized (lock) {
Count2 + +;
}
}
}
});
}
Start=System. CurrentTimeMillis ();
For (Thread t: threads) t.s tart ();
For (Thread t: threads) t.j oin ();
End=System. CurrentTimeMillis ();
System. The out. Println (" synchronized using Runnable anonymous classes: "+ count2 +" time: "+ (end - start));
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
The Object lockb=new Object ();
for(int i=0; I & lt; Threads. Length; I++) {
Threads [I]=
New Thread (() - & gt; {
/* @ Override
Public void the run () {*/
For (int k=0; K & lt; 100000; K++) {
Synchronized (lockb) {
Count4 + +;
}
}
});
}
Start=System. CurrentTimeMillis ();
For (Thread t: threads) t.s tart ();
For (Thread t: threads) t.j oin ();
End=System. CurrentTimeMillis ();
System. The out. Println (" synchronized anonymous classes: "+ count4 +" time: "+ (end - start));
CodePudding user response:
Running results areSynchronized using the Runnable anonymous class: 100000000 time: 6502
Synchronized anonymous class: 100000000 time: 3889
Why the difference so big?