天天看點

初學Java多線程:使用Runnable接口建立線程

這篇初學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多線程的學習又更近一步了。