Home >Java >javaTutorial >How to implement Runnable interface in Java?
But the Java Runnable interface does not have any support for threads. We must also create an instance of the Thread class, which 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(); } }
Using the Java Runnable interface to implement multi-threading allows us to contain all code in one class, which is conducive to encapsulation. Let us study some issues in the use of multi-threading.
The above is the detailed content of How to implement Runnable interface in Java?. For more information, please follow other related articles on the PHP Chinese website!