Home  >  Article  >  Java  >  How to implement the Runnable interface to create a thread class in java

How to implement the Runnable interface to create a thread class in java

王林
王林forward
2023-05-06 10:40:101611browse

Implement the Runnable interface to create a thread class

Runnable implementation steps:

  1. Define the Runnable interface implementation class, override the run() method, run( ) method represents the task to be completed by the thread, and the run() method is called the thread execution body.

  2. Create an instance of the Runnable implementation class. Runnable itself is a method of the Thread class, so when creating a thread, you must also implement a Thread class to wrap the Runnable object.

  3. Call the start() method of the thread object to start the thread.

<code>public class RunnableDemo implements Runnable{<br><br>    String threadName;<br><br>    public RunnableDemo(String threadName) {<br>        this.threadName = threadName;<br>    }<br><br>    @Override<br>    public void run() {<br>        for(int i=0;i<10;i++) {<br>            System.out.println(threadName+":" + i);<br>        }<br>    }<br><br>    public static void main(String args[]) {<br>        new Thread(new RunnableDemo("A")).start();<br>        new Thread(new RunnableDemo("B")).start();<br>    }<br>}</code>

The above is the detailed content of How to implement the Runnable interface to create a thread class in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete