1. 程式人生 > >實現多線程的兩種方式

實現多線程的兩種方式

out 兩種 sta main AD style HR 而是 實現

1.繼承Thread類。

源碼結構:public class Thread implements Runnable

從中可以看出Thread類實現了Runnable,由於java中不支持多繼承,所以實現多線程時,可以采用實現Runnable的方式。

2.實現Runnable接口。

註意一下聲明與調用不僅僅只是new一下,start一下,而是new兩下,start一下:

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("運行中!");
    }
}
public class MainTest { public static void main(String[] args) { Runnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); // runnable.run();這種調用不會啟動線程,只是單純的方法調用 System.out.println("運行結束!"); } }

實現多線程的兩種方式