Home > Java > javaTutorial > body text

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

王林
Release: 2023-05-06 10:40:10
forward
1655 people have browsed it

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

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!