let’s say I have a method doWork(). How do I call it from a separate thread (not the main thread).
let’s say I have a method doWork() . How do I call it from
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Create a class that implements the
Runnableinterface. Put the code you want to run in therun()method – that’s the method that you must write to comply to theRunnableinterface. In your “main” thread, create a newThreadclass, passing the constructor an instance of yourRunnable, then callstart()on it.starttells the JVM to do the magic to create a new thread, and then call yourrunmethod in that new thread.Take a look at Java’s concurrency tutorial to get started.
If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at
Future,Callable,Executorclasses in thejava.util.concurrentpackage.