PackageA.thread; Public classA {Private Static intx = 0; Public voidrun () {//Synchronizing code blocks synchronized( This) { for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "=====;x=" +x); Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } x++; } } } //Synchronization Method Public synchronized voidAA () { for(inti = 0; I < 10; i++) {System.out. println (Thread.CurrentThread (). GetName ()+ "====;x=" +x); X++; } }}View Code
PackageA.thread; Public classMAINB { Public Static voidMain (string[] args) {FinalA A1 =NewA (); thread[] Threads=NewThread[5]; for(inti = 0; I < 5; i++) {Threads[i]=NewThread (NewRunnable () { Public voidrun () {A1.AA (); A1.run (); } }); Threads[i].setname ("Threads" +i); Threads[i].start (); Try{threads[i].sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } } for(inti = 0; I < 5; i++) { Try{threads[i].join (); } Catch(interruptedexception e) {e.printstacktrace (); } } }}View Code
The synchronization method---using the synchronized adornment method:
access modifier synchronized [static] data return type method name () {
...........
}
Prevents multiple threads from accessing the synchronized static method in this class at the same time. Static can be omitted, which can work on all object instances of the class.
The synchronous statement block---only mutually exclusive access to the resources of this chunk:
Synchronized (Shared object name) {
Code snippets that are synchronized
}
1) It locks the current object corresponding to the shared object name.
2) Implementing a synchronization block in a thread is typically added in the Run method.
Java thread Synchronization