初學Java多線程:使用Runnable接口創建線程
作者:nokiaguy
這篇初學Java多線程系列為你講解如何使用Runnable接口創建線程。實現Runnable接口的類必須使用Thread類的實例才能創建線程。
實現Runnable接口的類必須使用Thread類的實例才能創建線程。通過Runnable接口創建線程分為兩步:
1. 將實現Runnable接口的類實例化。
2. 建立一個Thread對象,并將第一步實例化后的對象作為參數傳入Thread類的構造方法。
最后通過Thread類的start方法建立線程。
下面的代碼演示了如何使用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();
- }
- }
上面代碼的運行結果如下:
MyThread1
MyThread2
舉例Java多線程的學習又更近一步了。
【編輯推薦】
責任編輯:yangsai
來源:
真的有外星人嗎