public class ThreadImpl01 extends Thread { private int ticket = 5; @Override public void run() { for (int i = 0; i < 10; i++) { if (ticket > 0) { System.out.println("[ThreadImpl01] = " + ticket--); } } } }
public class ThreadImpl02 implements Runnable { private int ticket = 5; @Override public void run() { for (int i = 0; i < 10; i++) { if (ticket > 0) { System.out.println("[ThreadImpl02] = " + ticket--); } } } }
public class ThreadDemo { public static void main(String[] args) { /** * The advantages of implementing the Runnable interface over inheriting the Thread class: * 1. It can avoid the limitations caused by the single inheritance feature of Java; * 2. Enhance the robustness of the program, the code can be shared by multiple threads, and the code and data are independent; * 3. It is suitable for the case where multiple thread areas of the same program code process the same resource. */ new ThreadImpl01().start(); new ThreadImpl01().start(); new ThreadImpl01().start(); ThreadImpl02 threadImpl02 = new ThreadImpl02(); new Thread(threadImpl02).start(); new Thread(threadImpl02).start(); new Thread(threadImpl02).start(); } }