How to run a class' method using thread - java

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();

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();
}
};

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 ");
}
}

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 :(

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);
}});

Related

How to create n threads and work with all of them

Im trying to create a given number of threads and treat them at the same time to make a "race" program. The threads are created but im doing something wrong because any of the threads prints "Hi".
public class Principal implements Runnable{
public static void main(String[] args) {
int howManyThreads = 3;
Thread thread[];
thread = new Thread[howManyThreads];
for ( int i=0; i < thread.length; i++ ){
thread[i]= new Thread();
thread[i].setName("Thread - " + i);
}
for ( int i=0; i < thread.length; ++i){
thread[i].start();
System.out.println(thread[i].getName() + " - " + thread[i].getState());
}
}
public void run() {
System.out.println("Hi");
}
}
The default constructor for the Thread class creates a thread that does nothing. You're calling that default constructor here: thread[i] = new Thread();
If you want the thread to actually do something, then you must provide a Runnable instance as an argument to the Thread constructor. There are a couple of ways to do that. The newest, most concise way is to use a lambda expression:
thread[i] = new Thread(() -> {
System.out.println("Hi");
});
The Runnable interface is an #FunctionalInterface. Since the compiler knows that the Thread(...) constructor wants an object of that type, it infers that that's what the lambda should create, and the body of the lambda becomes the run() method of the new object.
Another, older way to provide a Runnable object is to use an anonymous inner class expression. The syntax is a little more cumbersome because you have to explicitly say what interface the new class should implement, and you have to explicitly declare the run() method:
thread[i] = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Hi");
}
});
The oldest way, still even more verbose, is to explicitly declare a named class:
class MyRunnable implements Runnable {
#Override
public void run() {
System.out.println("Hi");
}
};
public class Principal /*does not need to implement Runnable*/ {
...
thread[i] = new Thread(new MyRunnable());
...
}
You might ask, why did I remove implements Runnable from the Principal class, and create a whole new class?
I did it because, I've read this book: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/

How i can create new thread to do some task and stop the thread after the task finish

its seems to be a stupid question but I'm trying to create a task in a new thread, and after the task is finished the thread should exit without calling anything to stop it from main.
Here is an example:
public class Main {
public static void main(String[] args) {
// write your code here
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
}
}
class foo extends Thread{
void doSomething(){
// download File for example
}
}
if I implement the run method like this :
class foo extends Thread{
void doSomething(){
// download File for example
}
void run(){
doSomething();
}
}
it is going to call doSomething() method forever.
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
This is not the away to start a thread. Basically you call thread.start() method to start the thread which will execute everything which is there in run method.
Please go through the tutorial first
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Here is one solution:
public class ThreadExample extends Thread {
private void doSomething(){
System.out.println("Inside : doSomething()");
}
#Override
public void run() {
System.out.println("Inside : " + Thread.currentThread().getName());
doSomething();
}
public static void main(String[] args) {
System.out.println("Inside : " + Thread.currentThread().getName());
System.out.println("Creating thread...");
Thread thread = new ThreadExample ();
System.out.println("Starting thread...");
thread.start();
}
}
One output:
Inside : main
Creating thread...
Starting thread...
Inside : Thread-0
Inside : doSomething()
For further informations, check out this Java Concurrency and Multithreading tutorial.

Unexpected output. Please explain

I've been trying to figure out the reasons behind the output of the following Java program:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
new Thread(r).start();
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
runnable = r;
}
#Override
public void run() {
super.run();
System.out.println("Thread");
}
}
Output for above is : 'Implementation' followed by 'Thread' in next line. Now the problem lies in this statement :
gaurav.start();
As I have passed the runnable r to MyThread, I thought that r would get executed, hence, the output would be 'Implementation' for this too. But clearly, I am missing something. Also a difference between the statements:
new Thread(r).start();
gaurav.start();
for this scenario would be really useful. Thanks.
Consider the following:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
// calling Thread(Runnable r) constructor.
super(r);
// runnable isn't used anywhere. You can omit the following line.
runnable = r;
}
#Override
public void run() {
// First it will run whatever Runnable is given
// into Thread's constructor.
super.run();
System.out.println("Thread");
}
}
Output:
Implementation
Thread
I guess your confusion comes from your Runnable field in MyThread. You think that by having it there, you somehow override Thread's own runnable but you don't. If you want to do that, you should call super(r) in your constructor.
MyThread's start method will start the thread's run method in which you have System.out.println("Thread");
While new Thread(r).start(); will run the System.out.println("Implementation");
It's solely on OS's scheduler which thread would run first. So you might see the output as:
Implementation
Thread
Or
Thread
Implementation

Java and 2 threads

I am trying to learn Java's threads in order to do an assignment, but I do not understand how I can make each thread to do its own code. I also get an error:
Program.java:1: error: Program is not abstract and does not override abstract me
thod run() in Runnable
public class Program implements Runnable {
^
1 error
Because it is required by the assignment, I have to do everything within the same file, so I tried the code below:
public class Program implements Runnable {
Thread thread1 = new Thread () {
public void run () {
System.out.println("test1");
}
};
Thread thread2 = new Thread () {
public void run () {
System.out.println("test2");
}
};
public void main (String[] args) {
thread1.start();
thread2.start();
}
}
Could you please fix it for me and show how to have 2 threads which do different tasks from each other? I have already seen examples that print threads' names, but I did not find them helpful.
Thank you.
Your Program class is defined as implementing the Runnable interface. It therefore must override and implement the run() method:
public void run () {
}
Since your two Thread objects are using anonymous inner Runnable classes, you do not need and your should remove the implements Runnable from your Program class definition.
public class Program {
...
try this:
class Program {
public static void main(String[] args) {
Thread thread1 = new Thread() {
#Override
public void run() {
System.out.println("test1");
}
};
Thread thread2 = new Thread() {
#Override
public void run() {
System.out.println("test2");
}
};
thread1.start();
thread2.start();
}
Or you can create a separate class implementing Runnable and ovverriding method run().
Then in main method create an instance of Thread with you class object as argument :
class SomeClass implements Runnable {
#Override
run(){
...
}
}
and in main:
Thread thread = new Thread(new SomeClass());
When you implement an interface (such as Runnable) you must implement its methods, in this case run.
Otherwise for your app to compile and run just erase the implements Runnable from your class declaration:
public class Program {
public void main (String[] args) {
Thread thread1 = new Thread () {
public void run () {
System.out.println("test1");
}
};
Thread thread2 = new Thread () {
public void run () {
System.out.println("test2");
}
};
thread1.start();
thread2.start();
}
}

How can I pass a parameter to a Java Thread?

Can anyone suggest to me how I can pass a parameter to a thread?
Also, how does it work for anonymous classes?
You need to pass the parameter in the constructor to the Runnable object:
public class MyRunnable implements Runnable {
public MyRunnable(Object parameter) {
// store parameter for later user
}
public void run() {
}
}
and invoke it thus:
Runnable r = new MyRunnable(param_value);
new Thread(r).start();
For Anonymous classes:
In response to question edits here is how it works for Anonymous classes
final X parameter = ...; // the final is important
Thread t = new Thread(new Runnable() {
p = parameter;
public void run() {
...
};
t.start();
Named classes:
You have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Runnable is a much better solution than Thread BTW. So I'd prefer:
public class MyRunnable implements Runnable {
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void run() {
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
This answer is basically the same as this similar question: How to pass parameters to a Thread object
via constructor of a Runnable or Thread class
class MyThread extends Thread {
private String to;
public MyThread(String to) {
this.to = to;
}
#Override
public void run() {
System.out.println("hello " + to);
}
}
public static void main(String[] args) {
new MyThread("world!").start();
}
This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable without even declaring named class (handy for inliners):
String someValue = "Just a demo, really...";
new Thread(new Runnable() {
private String myParam;
public Runnable init(String myParam) {
this.myParam = myParam;
return this;
}
#Override
public void run() {
System.out.println("This is called from another thread.");
System.out.println(this.myParam);
}
}.init(someValue)).start();
Of course you can postpone execution of start to some more convenient or appropriate moment. And it is up to you what will be the signature of init method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.
In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:
String someValue = "Another demo, no serious thing...";
int anotherValue = 42;
new Thread(new Runnable() {
private String myParam;
private int myOtherParam;
// instance initializer
{
this.myParam = someValue;
this.myOtherParam = anotherValue;
}
#Override
public void run() {
System.out.println("This comes from another thread.");
System.out.println(this.myParam + ", " + this.myOtherParam);
}
}).start();
So all happens inside of the initializer block.
When you create a thread, you need an instance of Runnable. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:
public class MyRunnable implements Runnable {
private volatile String myParam;
public MyRunnable(String myParam){
this.myParam = myParam;
...
}
public void run(){
// do something with myParam here
...
}
}
MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();
If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:
public void setMyParam(String value){
this.myParam = value;
}
Once you have this, you can change the value of the parameter by calling like this:
myRunnable.setMyParam("Goodbye World");
Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.
I know that I'm a few years late, but I came across this issue and took an unorthodox approach. I wanted to do it without making a new class, so this is what I came up with:
int x = 0;
new Thread((new Runnable() {
int x;
public void run() {
// stuff with x and whatever else you want
}
public Runnable pass(int x) {
this.x = x;
return this;
}
}).pass(x)).start();
You can either extend the Thread class or the Runnable class and provide parameters as you want. There are simple examples in the docs. I'll port them here:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeThread p = new PrimeThread(143);
p.start();
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
To create a thread you normally create your own implementation of Runnable. Pass the parameters to the thread in the constructor of this class.
class MyThread implements Runnable{
private int a;
private String b;
private double c;
public MyThread(int a, String b, double c){
this.a = a;
this.b = b;
this.c = c;
}
public void run(){
doSomething(a, b, c);
}
}
Either write a class that implements Runnable, and pass whatever you need in a suitably defined constructor, or write a class that extends Thread with a suitably defined constructor that calls super() with appropriate parameters.
In Java 8 you can use lambda expressions with the Concurrency API & the ExecutorService as a higher level replacement for working with threads directly:
newCachedThreadPool() Creates a thread pool that creates new threads
as needed, but will reuse previously constructed threads when they are
available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks.
private static final ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> {
myFunction(myParam1, myParam2);
});
See also executors javadocs.
As of Java 8, you can use a lambda to capture parameters that are effectively final. For example:
final String param1 = "First param";
final int param2 = 2;
new Thread(() -> {
// Do whatever you want here: param1 and param2 are in-scope!
System.out.println(param1);
System.out.println(param2);
}).start();
Parameter passing via the start() and run() methods:
// Tester
public static void main(String... args) throws Exception {
ThreadType2 t = new ThreadType2(new RunnableType2(){
public void run(Object object) {
System.out.println("Parameter="+object);
}});
t.start("the parameter");
}
// New class 1 of 2
public class ThreadType2 {
final private Thread thread;
private Object objectIn = null;
ThreadType2(final RunnableType2 runnableType2) {
thread = new Thread(new Runnable() {
public void run() {
runnableType2.run(objectIn);
}});
}
public void start(final Object object) {
this.objectIn = object;
thread.start();
}
// If you want to do things like setDaemon(true);
public Thread getThread() {
return thread;
}
}
// New class 2 of 2
public interface RunnableType2 {
public void run(Object object);
}
You can derive a class from Runnable, and during the construction (say) pass the parameter in.
Then launch it using Thread.start(Runnable r);
If you mean whilst the thread is running, then simply hold a reference to your derived object in the calling thread, and call the appropriate setter methods (synchronising where appropriate)
There is a simple way of passing parameters into runnables.
Code:
public void Function(final type variable) {
Runnable runnable = new Runnable() {
public void run() {
//Code adding here...
}
};
new Thread(runnable).start();
}
No you can't pass parameters to the run() method. The signature tells you that (it has no parameters). Probably the easiest way to do this would be to use a purpose-built object that takes a parameter in the constructor and stores it in a final variable:
public class WorkingTask implements Runnable
{
private final Object toWorkWith;
public WorkingTask(Object workOnMe)
{
toWorkWith = workOnMe;
}
public void run()
{
//do work
}
}
//...
Thread t = new Thread(new WorkingTask(theData));
t.start();
Once you do that - you have to be careful of the data integrity of the object you pass into the 'WorkingTask'. The data will now exist in two different threads so you have to make sure it is Thread Safe.
One further option; this approach lets you use the Runnable item like an asynchronous function call. If your task does not need to return a result, e.g. it just performs some action you don't need to worry about how you pass back an "outcome".
This pattern lets you reuse an item, where you need some kind of internal state. When not passing parameter(s) in the constructor care is needed to mediate the programs access to parameters. You may need more checks if your use-case involves different callers, etc.
public class MyRunnable implements Runnable
{
private final Boolean PARAMETER_LOCK = false;
private X parameter;
public MyRunnable(X parameter) {
this.parameter = parameter;
}
public void setParameter( final X newParameter ){
boolean done = false;
synchronize( PARAMETER_LOCK )
{
if( null == parameter )
{
parameter = newParameter;
done = true;
}
}
if( ! done )
{
throw new RuntimeException("MyRunnable - Parameter not cleared." );
}
}
public void clearParameter(){
synchronize( PARAMETER_LOCK )
{
parameter = null;
}
}
public void run() {
X localParameter;
synchronize( PARAMETER_LOCK )
{
localParameter = parameter;
}
if( null != localParameter )
{
clearParameter(); //-- could clear now, or later, or not at all ...
doSomeStuff( localParameter );
}
}
}
Thread t = new Thread(new MyRunnable(parameter));
t.start();
If you need a result of processing, you will also need to coordinate completion of MyRunnable when the sub-task finishes. You could pass a call back or just wait on the Thread 't', etc.
Specially for Android
For callback purposes I usually implement my own generic Runnable with input parameter(s):
public interface Runnable<TResult> {
void run(TResult result);
}
Usage is simple:
myManager.doCallbackOperation(new Runnable<MyResult>() {
#Override
public void run(MyResult result) {
// do something with the result
}
});
In manager:
public void doCallbackOperation(Runnable<MyResult> runnable) {
new AsyncTask<Void, Void, MyResult>() {
#Override
protected MyResult doInBackground(Void... params) {
// do background operation
return new MyResult(); // return resulting object
}
#Override
protected void onPostExecute(MyResult result) {
// execute runnable passing the result when operation has finished
runnable.run(result);
}
}.execute();
}
Create a local variable in your class that extends Thread or implements Runnable.
public class Extractor extends Thread {
public String webpage = "";
public Extractor(String w){
webpage = w;
}
public void setWebpage(String l){
webpage = l;
}
#Override
public void run() {// l is link
System.out.println(webpage);
}
public String toString(){
return "Page: "+webpage;
}}
This way, you can pass a variable when you run it.
Extractor e = new Extractor("www.google.com");
e.start();
The output:
"www.google.com"
First I want to point out that other answers are true.
However, using the parameter in the constructor may not be the best idea for all of you.
In many scenarios you will want to use "Anonymous Inner Class", and override the run() method, because defining specific class for every use is painful.
(new MyRunnable(){...})
And at the time you create that Runnable, the parameter may not be available to you to pass it in the constructor. If for example, you pass this object to a method, that will perform some work in separate thread and then call your runnable, applying the result from that work to it.
In that case, using a method like this one:
public MyRunnable withParameter(Object parameter), may turn out to be far more useful choice.
I do not claim that this is the best solution to the problem, but it will get the job done.

Categories