Home  >  Article  >  Java  >  How can parameters be passed to Java threads?

How can parameters be passed to Java threads?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 21:19:03822browse

How can parameters be passed to Java threads?

Passing Parameters to Java Threads

To pass parameters to a thread, you can use the constructor of the Runnable object to store the parameter for later use. The following code snippet demonstrates this:

<code class="java">public class MyRunnable implements Runnable {

   public MyRunnable(Object parameter) {
       // store parameter for later user
   }

   public void run() {
   }
}</code>

To invoke the thread with a specific parameter, you can use the following syntax:

<code class="java">Runnable r = new MyRunnable(param_value);
new Thread(r).start();</code>

Anonymous Classes

Anonymous classes can also be used to pass parameters to threads. The following code snippet shows how:

<code class="java">new Thread(new Runnable() {

   @Override
   public void run() {
       // code to be executed
   }

}).start();</code>

In this example, an anonymous class is created that implements the Runnable interface. The parameter can be passed to the thread in the constructor of the anonymous class.

The above is the detailed content of How can parameters be passed to Java threads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn