Hello Multithreading - 建立新執行緒

這個簡單的例子展示瞭如何在 Java 中啟動多個執行緒。請注意,不保證執行緒按順序執行,並且執行順序可能因每次執行而異。

public class HelloMultithreading {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new MyRunnable(i));
            t.start();
        }
    }

    public static class MyRunnable implements Runnable {

        private int mThreadId;

        public MyRunnable(int pThreadId) {
            super();
            mThreadId = pThreadId;
        }

        @Override
        public void run() {
            System.out.println("Hello multithreading: thread " + mThreadId);
        }

    }

}