The example of this article tells the Java mutual lock. Share it for everyone for your reference. The specific analysis is as follows:
Mutual locks are often used in multiple thread access exclusive resources. For example, multiple threads write a file at the same time. Although the mutual interview method is not efficient, it is very meaningful for some application scenarios
// There is no mutual locking situation (you can run to see the results of the operation): Public Class LockDemo {// Private Static Object Lock = New Object (); // Static guarantees that there is only one lock Private int i = 0; increasei () {// synchronized (lock) {for (int k = 0; k <10; k ++) {// Perform 10 increases 1 operation I ++;} system.out.println (thread.currenThread (). getName () + "thread, i present value:" + i); //}} public static void main (string [] args) {lockdemo ld = new lockDemo (); int threadnum = 1000; // select 1000 The thread makes the results more likely to observe mythread [] threads = new mythread [threadnum]; for (int i = 0; i <threads.length; i ++) {threads [i] = new mythread (ld); // All threads are shaped by One LockDemo object threads [i] .start ();}} Class Mythreads Threads Thread {LockDemo Ld; Public Mythread (LockDemo LD) {this.ld = ld;} public run () {ld.increasei ();} } // After the mutual lock: Public Class LockDemo {Private Static Object Lock = New Object (); // Static guarantees that there is only one lock Private int i = 0; Public void increasei () {synnnnnnn chronize (lock) {for (INT K = 0; K <10; K ++) {// Perform I with 10 increases 1 operation I ++;} System.out.println (thread.currentthread (). GetName ()+"thread, i present value: " + i);}} Public Static void main (string [] args) {lockDemo ld = new lockDemo (); int threadnum = 1000; // Select 1,000 threads to make the results more likely to observe mythread [] Threads = new mythread [Threadnum]; for (int i = 0; I <THREADS.Length; I ++) {threads [i] = new mythread (ld); // All threads share a localdemo object threads [i] .start ();}} } Class Mythread Extends Thread {LockDemo LD; Public Mythread (LockDemo LD) {this.ld = ld;} Public void run () {ld.increasei ();}}}It is hoped that this article is helpful to everyone's Java program design.