In life we often encounter synchronization problems, and most of the actual problems are thread synchronization problems
Here's an example of a train ticket for life:
Suppose now we have a total of 1000 tickets to be sold, a total of 10 points of sale, then when the ticket to the last only one ticket, each ticket point how to deal with the only ticket? Or for a ticket, if it is in the ticket Station 1 ticket sales process, but has not been sold, then at this time, other ticket station how to deal with this ticket?
At this point, you should consider using the synchronization mechanism in Java;
Method One: Use the Runnable interface to implement
Package thread; Public classTsynchronize { Public Static voidMain (string[]ages) {intL=Ten; Syn []s=NewSyn[l]; Thread [] t=NewThread[l];
//Create 10 train ticket ticketing points for(intI=0; i<l;i++) {S[i]=NewSyn (); T[i]=NewThread (S[i]); T[i].setname ((i+1)+"Port number"); }
//Start thread for(intI=0; i<l;i++) {T[i].start (); } } }classSyn implements runnable{Private Static intCount= +; //Total number of votes Private StaticString key="Key"; //synchronized is to achieve synchronization, where the code block is either fully executed or not executed at all//synchronized If a function is decorated, it refers to the object of the function that called it, which does not require a string, the default is this, and if the code block is decorated , a string is used Public voidrun () { while(count>0) {synchronized (key) {//synchronized can be decorated with functions and code blocks when the key thread executes the token password, which can be any value if(count>0) {System. out. println ("Section"+thread.currentthread (). GetName () +"in the sale of first"+(1001-count) +"Ticket"); Count--; }Else{ Break; }}} System. out. println ("Section"+thread.currentthread (). GetName () +"the tickets have been sold out."); }}
Execution Result:
Method Two: Inherit the thread class:
Packagethread; Public classTsynclass { Public Static voidMain (String []ages) {intl=10; Point[] P=NewPoint[10]; for(inti=0;i<l;i++) {P[i]=NewPoint (); P[i].setname ((i+1) + "Port No."); } for(inti=0;i<l;i++) {P[i].start (); } }}classPointextendsthread{Private Static intCount = 1000;//number of votes shared Private StaticString key= "Key";//share the thread password and let it compete Public voidrun () { while(count>0){ synchronized(key) {//Two threads of key are own, not public if(count>0) {System.out.println ("No." + This. CurrentThread (). GetName () + "Buying First" + (1001-count) + "Ticket"); Count--; }Else{ Break; }}} System.out.println ("No." + This. CurrentThread (). GetName () + "The ticket has been sold out"); }}
Execution Result:
Synchronization problems in Java threads