Suppose a 5 person wants to surf the internet at the same time
Each person has 1-5 minutes of time to wait.
Lock synchronization situation: Queued to the Internet, everyone in their own time after the internet came out.
static method synchronization Code
classPersonextendsthread{PrivateRandom r =NewRandom (); Private intNum; PublicPerson (intNum) { This. Num =Num; } Public voidrun () {toileting (Num, R.nextint (4) + 1); } Public Static synchronized voidToileting (intTNo2,intTime ) { for(inti = 0; I < time; i++) {System.out.println ("First" + TNo2 + "bit, on" + i + "Minutes"); } }} Public classSetTest01 { Public Static voidMain (string[] args) {//Five Persons for(inti = 0; I < 4; i++) { NewPerson (i). Start (); } }}
View Code
Code block synchronization Code
classPersonextendsthread{PrivateRandom r =NewRandom (); Private intNum; PublicPerson (intNum) { This. Num =Num; } Public voidrun () {synchronized(person.class) {//lock can be customized here, but must be the same, with different locks invalid for(inti = 0; i < Num; i++) {System.out.println ("First" + Num + "bit," + i + "Minutes"); } } }} Public classSetTest01 { Public Static voidMain (string[] args) {//Five Persons for(inti = 0; I < 4; i++) { NewPerson (i). Start (); } }}
View Code
No. 0 Place, on the No. 0 place in 0 minutes, on the 1-minute No. 0 place, on the 2-minute No. 0 place, on the 3-minute 2nd, on the 0-minute 2nd, on the 1-minute 2nd, on the 2-minute 1th, on the 0-minute 1th, on the 1-minute 1th, on the 2-minute 1th, on the 3-minute 3rd, on the 0-minute 3rd Bit, on the 3rd place in 1 minutes, for 2 minutes
Not locked out of sync: a person would have been 3 minutes in succession, the results on 1 minutes out. The second person went in, would have been 5 minutes in a row, the result of 2 minutes out of the ... Until the end.
1th Place, on the 0-minute 3rd place, on the 0-minute No. 0, on the 0-minute 2nd, on the 0-minute No. 0, on the 1-minute 3rd, on the 1-minute No. 0, on the 2-minute 2nd, on the 1-minute No. 0, on 3 minutes 3rd, on 2 minutes
Java thread Synchronization