Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

java - Best way of creating and using an anonymous Runnable class

I want to use an anonymous class for Runnable. There are two ways, but I don't know if they do the same thing or not:

Method one: using Runnable directly and then calling run():

new Runnable() {
    @Override
    public void run() {
    }
}.run();

Method two: create an anonymous Runnable and paste to Thread, using the start() method instead of run():

new Thread(new Runnable() {
    @Override
    public void run() {
    }
}).start();

I think method two is obviously true. But, I don't know if it does the same thing as method one. Can we call the run() method on a Runnable directly?

question from:https://stackoverflow.com/questions/12771500/best-way-of-creating-and-using-an-anonymous-runnable-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you usually won't call run() directly on a Runnable as you will get no background threading that way. If you don't want and need a background thread, then fine call run() directly, but otherwise if you want to create a background thread and run your Runnable from within it, you must create a new Thread and then pass in the Runnable into its constructor, and call start().

Also, there are other ways of accomplishing this task including use of Executors and ExecutorServices, and you should look into the uses of this as they offer more flexibility and power than using a bare bones Thread object.

Also you'll want to have a look at use of the Future interface and the FutureTasks class that are like Runnables only they allow you to return a result when complete. If you've used a SwingWorker, then you've already used a Future interface without realizing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...