One Java question every day [11] and one java question 11
Question
How does synchronized implement thread synchronization? Modify the MyRunnableThread class in every Java question [10] to solve the problem where all three threads get 10.
Answer
Method 1:
Use the synchronized keyword to wrap code blocks that require thread security to achieve thread synchronization. Syntax format:
Synchronized (expression) {// code to be Synchronized}
The MyRunnableThread class in a Java question [10] Every day is changed:
package me.huangzijian;public class MyRunnableThread implements Runnable { private int num = 10; private Object obj = new Object(); @Override public void run() { int count = num; for (int i = 0; i < count; i++) { synchronized (obj) { System.out.println(Thread.currentThread().getName() + ":" + num); num--; } } }}
Method 2:
The synchronized keyword is used to modify the method, and the whole method is used for process thread synchronization. Syntax format:
Public synchronized void function () {// method code}
The MyRunnableThread class in a Java question [10] Every day is changed:
package me.huangzijian;public class MyRunnableThread implements Runnable { private int num = 10; private Object obj = new Object(); @Override public synchronized void run() { int count = num; for (int i = 0; i < count; i++) { System.out.println(Thread.currentThread().getName() + ":" + num); num--; } }}
Divergent thinking
1. synchronized keyword modifier. If no expression exists, how does it obtain the synchronization lock?
Answer:
2. For method 1, if all objects passed to synchronized are new, can the synchronization effect be achieved?
A: No. Because different threads correspond to different synchronization locks and are not exclusive, thread synchronization will become invalid.