简体   繁体   中英

Is there a way to thread methods in java, instead of the entire class?

So I've been wondering, recently, in school, we've been learning about java threads..

Unlike most other languages, I haven't found a way to thread a function in java yet, which is really what I'm looking for...

I know one could use the run class, but imagine a class has 3 functions, each with their own parameters, i'd like to be able to call those functions and thread them seperatly if possible...

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

The correct approach to achieve multi-threading in Java is to implement Runnable . Extending the Thread class is just a convenient slightly simpler way, but implementing the Runnable interface is best, because it gives you the method run() in which you can call your function and also allows you to extend other classes instead of Thread .

What you don't have access to however is the return value of the function you are executing in the other Thread. For this you can use the Future which gives you an object which will get populated with your return value, as soon as the other thread executes the function. Instead of implementing Runnable you implement Callable , which is very similar, with its method called call() instead of run() , and allowing you to specify the return type through Generics. Future objects can also be used with thread pools and task executors. Look at the example in the javadoc of the Future class, it has a good example and explanation.

Also remember that within a method you can create an anonymous class, so if you're simply after that you just do it inline (extending Runnable or Callable ) within the method you want to execute in a separate thread. (As Cruncher indicated in his answer)

You have to create separate wrapper classes that either implement Runnable or extend thread and call your functions.

BTW even if java had kind of method pointers like C has you still need some wrapper that knows the values of parameters you want to pass to the functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM