實現Runnable接口的類必須使用Thread類的實例才能建立線程。經過Runnable接口建立線程分爲兩步:java
1.將實現Runnable接口的類實例化。多線程
2.創建一個Thread對象,並將第一步實例化後的對象做爲參數傳入Thread類的構造方法。學習
最後經過Thread類的start方法創建線程。spa
下面的代碼演示瞭如何使用Runnable接口來建立線程:線程
package mythread; public class MyRunnable implements Runnable { public void run() { System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) { MyRunnable t1 = new MyRunnable(); MyRunnable t2 = new MyRunnable(); Thread thread1 = new Thread(t1, 「MyThread1」); Thread thread2 = new Thread(t2); thread2.setName(「MyThread2」); thread1.start(); thread2.start(); } }
上面代碼的運行結果以下:code
MyThread1 MyThread2
舉例Java多線程的學習又更近一步了。對象