Java anonymous classes and synchronization and “this”

I'm dealing with a competitive condition that I believe in my java GUI

I have some methods to create an "anonymous method" in an anonymous class, as follows:

synchronized foo()
{
     someMethod(new TimerTask()
     {
          public synchronized run()
          {

               //stuff

          }
     };
}

Question: do you want to run method synchronization on the class where the TimerTask object or foo is located?

Question2: if I get rid of "synchronized" in the run () declaration and there is a synchronized (this) {} block in the run () body, "this" refers to the TimerTask object or an instance of the method containing foo()?

Please help me here

Thank you, JBU

Solution

The running method is synchronized on the TimerTask itself Instance methods are always synchronized on this object (the class method synchronizes on the class object.)

If you want to synchronize on its object, you need to qualify the this keyword Assuming foo () is a member of the bar class in the run () method of the timer class, you can use

public void run() {
  synchronized(Bar.this) {
    ...
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>