Java Synchronized method…not synchronized

后端 未结 3 660
时光取名叫无心
时光取名叫无心 2021-01-21 12:14

For my current java exercise, I have to get mail from 2 different gmail accounts. I have done this by creating new instances of my gmail class. The gmail class extends thread, a

3条回答
  •  孤城傲影
    2021-01-21 12:43

    When you synchronize readMail() as a method, then only one thread at a time can access the Objects readMail() method. If you have two different object instances of type GMail with a readMail() method, two threads can access them both unsynchronized (in parallel).

    In other words, the semaphor that block execution of the readMail() method is in fact the GMail object. With two different object instances, you have two semaphores which do not interact.

    It would work if you had only one instance of a GMail object with a synchronized readMail() method. Then only one thread at a time could access it.

提交回复
热议问题