Threadsafe vs Synchronized

前端 未结 7 1357
刺人心
刺人心 2021-02-02 11:01

I\'m new to java. I\'m little bit confused between Threadsafe and synchronized. Thread safe means that a method or class instance can be used by multiple threads at the same tim

7条回答
  •  暖寄归人
    2021-02-02 11:25

    Synchronized: only one thread can operate at same time. Threadsafe: a method or class instance can be used by multiple threads at the same time without any problems occurring. If you relate this question as, Why synchronized methods are thread safe? than you can get better idea.

    As per the definition this appears to be confusive. But not,if you understand it analytically.

    Synchronized means: sequentially one by one in an order,Not concurrently [Not at the same time]. synchronized method not allows to act another thread on it, While a thread is already working on it.This avoids concurrency. example of synchronization: If you want to buy a movie ticket,and stand in a queue. you will get the ticket only after the person in front of you get the ticket.

    Thread safe means: method becomes safe to be accessed by multiple threads without any problem at the same time.synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access. Actually, Even they act at the same time, but cannot access the same resource(method/block) at the same time, because of synchronized behavior of the resource.

    Because If a method becomes synchronized, so this is becomes safe to allow multiple threads to act on it, without any problem. Remember:: multiple threads "not act on it at the same time" hence we call synchronized methods thread safe.

    Hope this helps to understand.

提交回复
热议问题