Reputation: 17454
If I do the following, I will be able to create an object as a thread and run it.
class ThreadTest
{
public static voic main(String[] args)
{
HelloThread hello = new HelloThread();
Thread t = new Thread(hello);
t.start();
}
}
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
}
Now, if my HelloThread
class has a another method call runThisPlease()
, how are we supposed to run it with a thread?
Example:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
public void runThisPlease(String input)
{
System.out.println (" Using thread on another class method: " + input );
}
}
Que: When I try Thread t = new Thread(hello.runThisPlease());
, it doesn't work. So how can we call the method runThisPlease()
using a thread?
Edit: Argument needed in method for runThisPlease()
;
Upvotes: 0
Views: 739
Reputation: 82461
In java 8 you can use
Thread t = new Thread(hello::runThisPlease);
hello::runThisPlease
will be converted to a Runnable
with a run method that calls hello.runThisPlease();
.
If your want to call a method, that needs parameters, e.g. System.out.println
, you can of course use a normal lambda expression too:
final String parameter = "hello world";
Thread t = new Thread(() -> System.out.println(parameter));
If you use a java version < 8, you can of course replace the method reference / lambda expression with anonymus inner classes that extend Runnable
(which is what a java8 compiler does, AFAIK), see other answers.
However you can also use a anonymus inner class that extends Thread
:
final HelloThread hello = //...
Thread t = new Thread() {
@Override
public void run() {
hello.runThisPlease();
}
};
Upvotes: 4
Reputation: 138
You have to only call this method inside run()
method.
public void run(){
System.out.println(" Hello ");
runThisPlease();
}
If you want to pass some argument then you can use below code
String str = "Welcome";
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(str);
}});
Upvotes: 0
Reputation: 4475
Things are maybe more clear if you use the Runnable interface:
public class HelloThread implements Runnable
{
@Override
public void run() {
// executed when the thread is started
runThisPlease();
}
public void runThisPlease() {...}
}
To launch this call:
Thread t=new Thread(new HelloThread());
t.start();
The Thread class can not see your extra method because it is not part of the Runnable interface. As a convenience Thread implements Runnable but I don't think it helps in clarity :(
Upvotes: 0
Reputation: 7804
Simply calling the runThisPlease()
from within the run()
method will make it part of a new thread.
Try this:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello .. Invoking runThisPlease()");
runThisPlease();
}
public void runThisPlease()
{
System.out.println (" Using thread on another class method ");
}
}
Upvotes: 0