0

While looking up pieces of code that can cause deadlocks using threads, I came across this piece of code :

Thread t1 = new Thread(){
        public void run(){
            while(true){
                synchronized(str1){
                    try {
                        Thread.sleep(10);
                        } catch (InterruptedException e) {
                    }
                    synchronized(str2){
                        System.out.println(str1 + "::"+str2);
                    }
                }
            }

        }

    };

After declaring and instantiating a Thread object, it seems inside that thread the run method is written with accompanying logic and the Thread definition ends by closing the brace with semi colon .

What is the name of such a block of code? Is this what is called as an anonymous block?

Eran
  • 387,369
  • 54
  • 702
  • 768
The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
  • Yes its anonymous class. – SMA Nov 15 '14 at 12:34
  • It's an "anonymous class". https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html – JB Nizet Nov 15 '14 at 12:34
  • possible duplicate of [Creating the instance of abstract class or anonymous class](http://stackoverflow.com/questions/16785922/creating-the-instance-of-abstract-class-or-anonymous-class) – Joe Feb 03 '15 at 11:04

1 Answers1

1

This is an anonymous class isntance. This code creates an instance of an anonymous class (i.e. it has no name) that extends Thread class and overrides its run method.

Eran
  • 387,369
  • 54
  • 702
  • 768