[Java concurrent programming learning] 1. Two ways to realize multithreading

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325970788&siteId=291194637