是否可以在以下对象中同步对象“ callme”:new Thread(()-> callme.call(“ First”))。start();

问题描述 投票:-3回答:1

只是试图了解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()方法的调用未同步如何将调用与方法调用同步?

java multithreading lambda syntax synchronization
1个回答
0
投票

从语法上讲,可以使用同步块

© www.soinside.com 2019 - 2024. All rights reserved.