Java Runnable Question

I am currently teaching a course in Java, and I came across some confusing code.

Example:

Runnable runnable = new Runnable()
        {
            public void run()
            {
                //doStuff
            }
        };

I really don't understand what this code does.

How can a start method be associated with an instance of a class?

I googled "Runnable" and found out that it is an interface. Am I implementing an interface by declaring a run method between curly braces? Can this be done for any interface in java?

I could use some links / explanations. Thank!

+5
source share
4 answers

, Runnable. , , , - ( " " ). , :

// Define it
class Foo implements Runnable
{
    public void run()
    {
        // Do stuff
    }
}

// And then use it
Runnable runnable = new Foo();

... , Foo ( "" ) . .

+8

, , . , .

, , , , . , . .

+2

googled "Runnable" . run ? java?

!

, Runnable. , , , . , Java Runnable ( ).

:

Runnable runnable = new Runnable()
        {
            public void run()
            {
                System.out.println("I'm running");
            }
        };
runnable.run();

" ".

+2

.... test runna = new test()

class test implements Runnable{
        test(){
            Thread t = new Thread(this);
            t.start();
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while(true){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.print("asd");
            }
        }

    }
0
source

All Articles