Synchronous multithreading in Java

I teach myself Java. I want to know about multithreading I created the myThread class, whose job executes a loop until the condition is true, and then prints information about it It contains static fields that are incremented in the constructor and decremented when the job completes Class flag is to "tell" the thread when to start

Solution

Left and – left are not atomic operations When several threads attempt to execute, it may be that two attempts decrement to the left at the same time This behavior is because your code is synchronized at the instance level (print is an instance method) and left is a static (class) variable

Note also that the printed values in print () are out of order (because print is not statically synchronized, the printed "last" value may not be the value of the last thread calling print)

First change: check that the left is really zero after all threads are executed

Output:

The second change: synchronize on the class (add, delete and print are converted to static methods; we also need to replace the call print in the run, because the name in the static method print is no longer visible)

Output:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>