Home > Java > javaTutorial > body text

How to write a class that implements Runnable interface in Java?

WBOY
Release: 2023-05-09 19:52:15
forward
1641 people have browsed it

The Runnable interface has only one method, run(). We declare that our class implements the Runnable interface and provides this method, and writes our thread code into it to complete this part of the task.

But the Runnable interface does not have any support for threads. We must also create an instance of the Thread class. This is achieved through the constructor public Thread(Runnable target); of the Thread class. The following is an example:

public class MyThread implements Runnable  {   int count= 1, number;   public MyThread(int num)  {   numnumber = num;   System.out.println("创建线程 " + number);   }   public void run()  {   while(true)  {   System.out.println  ("线程 " + number + ":计数 " + count);   if(++count== 6) return;   }   }   public static void main(String args[])  {   for(int i = 0; i 〈 5;  i++) new Thread(new MyThread(i+1)).start();   }   }
Copy after login

Strictly speaking, it is also feasible to create an instance of a Thread subclass, but it must be noted that the subclass must not override the run method of the Thread class, otherwise the thread will execute It is the run method of the subclass, not the run method of the class we use to implement the Runnable interface. You might as well try it out.

Using the Java Runnable interface to implement multi-threading allows us to contain all code in one class, which is conducive to encapsulation. Its disadvantage is that we can only use one set of code. If we want to create multiple threads and To make each thread execute different code, you still have to create an additional class. If this is the case, in most cases it may not be as compact as directly inheriting Thread from multiple classes.

The above is the detailed content of How to write a class that implements Runnable interface 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