Topic
Synchronized how to implement thread synchronization? Please modify the Myrunnablethread class in Java question [10] every day to solve the problem that three threads get 10.
Answer
Method One:
Thread synchronization is achieved by using the Synchronized keyword to wrap blocks of code that need to ensure thread safety. The syntax format is:
Synchronized (expression) { // code to be synchronized }
The Myrunnablethread class in the Java question [10] is modified to:
PackageMe.huangzijian; Public classMyrunnablethreadImplementsRunnable {Private intnum = 10; PrivateObject obj =NewObject (); @Override Public voidrun () {intCount =num; for(inti = 0; I < count; i++) { synchronized(obj) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +num); Num--; } } }}
Method Two:
Use the Synchronized keyword to modify the method to process thread synchronization using the entire method. The syntax format is:
Public synchronized void function () { // method code }
The Myrunnablethread class in the Java question [10] is modified to:
PackageMe.huangzijian; Public classMyrunnablethreadImplementsRunnable {Private intnum = 10; PrivateObject obj =NewObject (); @Override Public synchronized voidrun () {intCount =num; for(inti = 0; I < count; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +num); Num--; } }}
Divergent thinking
1.synchronized keyword retouching method, without expression, how does it get a sync lock?
Answer:
- For the synchronization method of the instance, use this, which is the current instance object as the synchronization lock.
- For a static synchronous method, the bytecode object of the current class is used.
2. For method One, if each pass to synchronized is a new object, can the effect of synchronization be achieved?
Answer: No. Thread synchronization is invalidated because different threads correspond to different synchronization locks and do not have exclusivity.
A Java question every day [11]