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

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

WBOY
WBOYforward
2023-05-09 19:52:151672browse

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();   }   }

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!

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