开发者

Explicit call of Runnable.run

Somebody, who was working on my code before me, created some method and passed Runnable as parameter, more likely:

void myMethod(Runnable runnable){ runnable.run(); }

Then calling myMethod out of main looks like:开发者_开发问答

public static void main(String args[]) 
{ try 
{ myMethod(new Runnable(){ public void run() { //do something...; }}); } 
catch (Throwable t) { } }

So, to supply parameter to myMethod I need to instantiate object of (in this case anonymous) class implementing Runnable.

My question is: is it necessary to use Runnable in this example? Can I use any different interface? I mean I can create new interface with single method i.e.

interface MyInterface{ void doThis(); }

then change look of myMethod: void myMethod(MyInterface myObject){ myObject.doThis(); }

And of course client too:

public static void main(String args[]) { 
try { myMethod(new MyInterface (){ public void doThis() 
{ //do something...; }}); } 
catch (Throwable t) { } }

Or maybe something is about Runnable?!


You could absolutely change the interface as you've suggested, but what is the point? What advantage does it bring to provide an instance of MyInterface rather than Runnable? One advantage of Runnable is that it would make it easier to make the code multi-threaded in the future, because most of the APIs that execute threads (e.g. Executor) work with instances of Runnable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜