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

How can parameters be passed to Java threads?

Susan Sarandon
Release: 2024-11-07 21:19:03
Original
916 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template