"Problem arises": For example, for the ticket system, there is the following code:
1 classHelloImplementsRunnable {2 Private Static intCount=5;3 Public voidrun () {4 for(inti=0;i<10;++i) {5 if(count>0){6 Try{7Thread.Sleep (1000);8}Catch(interruptedexception e) {9 e.printstacktrace ();Ten } OneSystem.out.println (count--); A } - } - } the - Public Static voidMain (string[] args) { -Hello he=Newhello (); -Thread h1=NewThread (He); +Thread h2=NewThread (He); -Thread h3=NewThread (He); + H1.start (); A H2.start (); at H3.start (); - } -}
"Run Results"
5
4
3
2
1
0
-1
Here comes the-1, obviously this is wrong. , the number of votes should not be negative.
If you want to solve this problem, you need to use synchronization. The so-called synchronization is that only one thread runs in the unified time period,
The other thread must wait until the thread finishes before it can continue execution.
"Use thread synchronization to resolve issues"
With synchronization, you can use Synchronous code block and synchronization method of two kinds to complete.
(i) Synchronizing code blocks
Syntax format:
Synchronized (synchronization object) {
Code that needs to be synchronized
}
However, the current object this is generally used as the synchronization object.
For example, the question of buying tickets above is as follows (Modify the Run method):
Public voidrun () { for(inti=0;i<10;++i) { synchronized( This){ if(count>0){ Try{Thread.Sleep (1000); }Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Count--); } } } }
"Run Result": (output one result per second)
5
4
3
2
1
(ii) Synchronization method
The syntax format is
Synchronized method return type method name (parameter list) {
Other code
}
Modify the Run method
Public voidrun () { for(inti = 0; I < 10; ++i) {sale (); } } Public synchronized voidSale () {if(Count > 0) { Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Count--); } }
The results of the operation are as above.
As a reminder, synchronization is required when multiple threads share a resource, but excessive synchronization can lead to deadlocks .
Threading issues--synchronization and deadlock