1.synchronized (object)
PackageTest.thread;Importjava.io.IOException;Importorg.junit.Test;/** Test Thread lock*/ Public classTestblock { Public Static voidMain (string[] args) {testblock test=NewTestblock (); MyTest Thread1= Test.NewMyTest (test); Thread1.setname ("1"); MyTest thread2= Test.NewMyTest (test); Thread2.setname ("2"); Thread1.start (); Thread2.start (); } /** Test Sync*/ classMyTestextendsthread{private Object o; Public MyTest (Object o) {this.o= o; } @Override Public voidrun () {//TODO auto-generated Method Stub synchronized(o) { //This o is an instance of the test object, the Class object instance is locked, when the thread calls an instance to run, and the other thread calls the instance to block, to achieve the purpose of locking Try { for(inta=0;a<3;a++) {System.out.println ("Thread" +mytest.currentthread (). GetName () + "Modify a==" +a); //Mytest.yield (); } } Catch(Exception e) {//Todo:handle Exception } } } } }
Results returned:
·
Thread 1 Modify A==0
Thread 1 Modify A==1
Thread 1 Modify a==2
Thread 1 Modify A==3
Thread 1 Modify a==4
Thread 1 Modify a==5
Thread 1 Modify A==6
Thread 1 Modify a==7
Thread 1 Modify A==8
Thread 1 Modify A==9
Thread 2 Modify A==0
Thread 2 Modify A==1
Thread 2 Modify a==2
Thread 2 Modify A==3
Thread 2 Modify A==4
Thread 2 Modify A==5
Thread 2 Modify A==6
Thread 2 Modify A==7
Thread 2 Modify A==8
Thread 2 Modify A==9
You can see that the second thread runs after a thread has finished running
2.synchronized (This)
PackageTest.thread;Importjava.io.IOException;Importorg.junit.Test;/** Test Thread lock*/ Public classTestblock { Public Static voidMain (string[] args) {testblock test=NewTestblock (); MyTest Thread1= Test.NewMyTest (test); Thread1.setname ("1"); MyTest thread2= Test.NewMyTest (test); Thread2.setname ("2"); Thread1.start (); Thread2.start (); } /** Test Sync*/ classMyTestextendsthread{PrivateObject o; PublicMyTest (Object o) { This. o=o; } @Override Public voidrun () {//TODO auto-generated Method Stub synchronized( This) { Try { for(inta=0;a<10;a++) {System.out.println ("Thread" +mytest.currentthread (). GetName () + "Modify a==" +a); //Mytest.yield (); } } Catch(Exception e) {//Todo:handle Exception } } } } }
Results returned:
Thread 1 Modify A==0
Thread 1 Modify A==1
Thread 1 Modify a==2
Thread 1 Modify A==3
Thread 1 Modify a==4
Thread 2 Modify A==0
Thread 1 Modify a==5
Thread 1 Modify A==6
Thread 1 Modify a==7
Thread 1 Modify A==8
Thread 1 Modify A==9
Thread 2 Modify A==1
Thread 2 Modify a==2
Thread 2 Modify A==3
Thread 2 Modify A==4
Thread 2 Modify A==5
Thread 2 Modify A==6
Thread 2 Modify A==7
Thread 2 Modify A==8
Thread 2 Modify A==9
The difference between Java synchronized (object/this)