How to Pass a Parameter to a Java Thread

How can I pass a parameter to a Java Thread?

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

Passing parameter to Java Thread

No, the run method never has any parameters. You'll need to put the initial state into the Runnable. If you're using an anonymous inner class, you can do that via a final local variable:

final int foo = 10; // Or whatever

Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(foo); // Prints 10
}
});

If you're writing a named class, add a field to the class and populate it in the constructor.

Alternatively, you may find the classes in java.util.concurrent help you more (ExecutorService etc) - it depends on what you're trying to do.

EDIT: To put the above into your context, you just need a final variable within the loop:

for (int i=0; i< threads.length; i++) {
final int foo = i;
threads[i] = new Thread(new Runnable() {
public void run() {
// Use foo here
}
});
}

How can I pass parameter to a Java thread?

In the Job.start() method, store the value in a member variable, so that you can access it in the run() method later, when the thread is started.

public abstract class Job implements Runnable {
protected Integer jobId;

public void start(Integer jobId) {
this.jobId = jobId;
try {
new Thread(this).start();
} catch (Exception e) {
e.getMessage();
}
}
}

public class Test extends Job {
@Override
public void run() {
System.out.println(jobId);
}
}

(Java Multi threading) How to pass parameter in multithreading?

There are syntactical and logical errors in your program:

I have corrected your code. Below code is the correct code for printing odd/even numbers using multi-threading in Java.

class jo extends Thread {
private int number;

jo(int number) {
this.number = number;
}

@Override
public void run() {
System.out.println("Odd numbers are:");
for (int i = 0; i <= number; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
}

class yo extends Thread {

private int number;

yo(int number) {
this.number = number;
}

@Override
public void run() {
System.out.println("Even Numbers are");
for (int i = 0; i <= number; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}

}
import java.util.Scanner;

class Star {
public static void main(String[] args) throws InterruptedException {
System.out.println("Enter No. upto which eve-od should be printed");
Scanner var = new Scanner(System.in);
int vary = var.nextInt();
jo money = new jo(vary);
yo honey = new yo(vary);

money.start();
Thread.sleep(5000);
honey.start();

}

}

Corrections done:

  1. In class Star, there was a syntax error when you were creating object of class jo

2.To achieve multithreading, you need to override run method of thread class. The correct signature of run method is public void run() { //logical code will go here } run method does not accept any input arguments.

3.To start execution of thread you need to invoke the start method of Thread class. It looks like public void start(). start method does not accept any input arguments.

4.I have done the logical correction in your code in jo and yo class. use % operator to check a given number is even or odd. % operator returns remainder, if a remainder comes zero when a number is divided by 2, it means it is a even number else it is odd.

You can run shared code to check the outputs.

Happy coding!

How to pass a parameter to a thread and get a return value?

This a job for thread pools. You need to create a Callable<R> which is Runnable returning a value and send it to a thread pool.

The result of this operation is a Future<R> which is a pointer to this job which will contain a value of the computation, or will not if the job fails.

public static class CalculationJob implements Callable<Integer> {
int input;

public CalculationJob(int input) {
this.input = input;
}

@Override
public Integer call() throws Exception {
return input + 1;
}
}

public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(4);

Future<Integer> result = executorService.submit(new CalculationJob(3));

try {
Integer integer = result.get(10, TimeUnit.MILLISECONDS);
System.out.println("result: " + integer);
} catch (Exception e) {
// interrupts if there is any possible error
result.cancel(true);
}

executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.SECONDS);
}

Prints:

result: 4

Passing parameters to Java Thread

I think the choice of "static int c" is incorrect as it means that all instances of ThreadParam will "share" (and poorly at that) a common value for c. That is to stay, if you have 2 separate ThreadParams going simultaneously, one of them is likely present the "wrong" value for C. Consider...

class BadThreadParam implements Runnable {
static int c;

public BadThreadParam( int a, int b ) {
c = a + b;
}

public void run() {
System.out.println( c );
}
}

class ImmutableThreadParam implements Runnable {
private final int c;

public ImmutableThreadParam( int a, int b ) {
c = a + b;
}

public void run() {
System.out.println( c );
}
}

public class BadThreadParamTest {
public static void main( String[] args ) {
BadThreadParam shouldBe3 = new BadThreadParam( 1, 2 );
BadThreadParam shouldBe5 = new BadThreadParam( 3, 2 );
shouldBe3.run(); // Expect 3 but is 5. WTF?
shouldBe5.run(); // Expect 5.

ImmutableThreadParam expect3 = new ImmutableThreadParam( 1, 2 );
ImmutableThreadParam expect5 = new ImmutableThreadParam( 3, 2 );
expect3.run(); // Expect 3.
expect5.run(); // Expect 5.
}
}

If you make the "c" local to the instance, you overcome the "2 separate ThreadParams are affecting the same value" problem. If you make the "private int c" final, you are avoiding the need for synchronization. If you need to mutate "c" down in the run (or from the outside), now you are entering the world of synchronization...

class ThreadSafeMutableThreadParam implements Runnable {
private int c;

public ThreadSafeMutableThreadParam( int a, int b ) {
c = a + b;
}

public synchronized void setC( int c ) {
this.c = c;
}

public synchronized int getC() {
return c;
}

public void run() {
System.out.println( getC() );
}
}

Other than that, tuxdna's is correct in describing how you "pass params to a Runnable". The Runnable is inconsequential; you are passing params to a class (however you achieve that). If you need them available down in a run(), you need to be aware of synchronization.

Call and pass parameter to method in another thread

Runnable#run is the method designed to do the actual work of a Runnable object. So you would have to make it do what you're currently doing in getPage.

You can use state to store url, and save the response in a different field. See further comments about how you can refactor this to simplify it even further. But from the current code, the simplest changes could be:

class Http implements Runnable {

//initialize Http. This can be done better perhaps
volatile OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true).build();

private Response response;

private String url;

public Http(String url) {
this.url = url;
}

@Override
public void run() {
this.getPage(this.url);
}

public void getPage(String url) {
Request request = new Request.Builder().url(url).build();

try {
this.response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}

And in your main method:

Http http = new Http("http://google.com");
Thread threadHttp = new Thread(http, "httpThread1");
threadHttp.start();
threadHttp.join();
Response resp = http.getResponse();

However, this can be substantially simplified with the use of futures. For example, it could look as simple as:

class Http {
volatile OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true).build();

public Response getPage(String url) {
Request request = new Request.Builder().url(url).build();

try {
this.response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}

And, using futures, your main method can look even simpler:

public static void main(String[] args) throws Exception {
Http http = new Http();
CompletableFuture<Response> future =
CompletableFuture.supplyAsync(() -> http.getPage("http://google.com"));

//the preceding statement will call `getPage` on a different thread.
//So you can do other things before blocking with next statement

Response resp = future.join();
}

You can even use a thread pool with supplyAsync if you need more control over how asynchronous tasks run.

Java: How to pass parameters into Thread method using lambda expression?

Your lambda can read final variables in the scope where it is defined.
So the easiest thing would be to make final variables for the things you want to pass into myMethod.

final int a = 1;
final int b = 2;
Thread myThread = new Thread(() -> { myMethod(a,b); });
myThread.start(); // don’t forget to execute it, just creating it won’t run the thread

Actually the variables can be “effectively final”, not technically final.
Make a variable and don’t change what’s in it, there isn’t a way for the lambda to detect changes in the variables. But it may be just as well to enforce it with final.

Otherwise don’t use a lambda, define a Runnable or Callable and pass in what it needs through the constructor.

It seems likely to me the real issue is not starting the thread as pointed out in the comments.



Related Topics



Leave a reply



Submit