只是试图了解java中的语法,
The call() method is not synchronized, is it possible to synchronise the object callme(from class Callme which has an unsynchronized method call()) in the below code?
new Thread(() -> callme.call("First")).start();
_________________________________________________
class Callme{
void call(String msg) {
try {
System.out.println("Message1" + msg);
Thread.sleep(1000);
System.out.println("Message2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class WithOutSynch {
public static void main(String[] args) {
Callme callme = new Callme();
new Thread(() -> callme.call("First")).start();
new Thread(() -> callme.call("Second")).start();
new Thread(() -> callme.call("Third")).start();
new Thread(() -> callme.call("Fourth")).start();
new Thread(() -> callme.call("Fifth")).start();
}
}
在上面的代码中,对call()方法的调用未同步如何将调用与方法调用同步?
从语法上讲,可以使用同步块