在線程的Tread對象上調用start()方法,而不是run()或者別的方法。
在調用Start方法之前,線程出於新狀態中,新狀態是指有一個Thread對象!但還沒有一個真正的線程。
在調用start之后發生了一系列復雜的事情
啟動新的執行線程(具有新的調用棧)
該線程從新狀態轉移到可運行狀態
當該線程獲得機會執行時,其目標run()方法將運行
在java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable接口。
對於直接繼承Thread的類來說,代碼大致框架是:
class 類名 extends Thread{ 方法1; 方法2; … public void run(){ // other code… } 屬性1; 屬性2; … }
class hello extends Thread { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "運行 " + i); } } public static void main(String[] args) { hello h1=new hello("A"); hello h2=new hello("B"); h1.start(); h2.start(); } private String name; }
線程的運行需要本地操作系統的支持。所以需要使用start()而不是直接使用run()。
通過實現Runnable接口:
class 類名 implements Runnable{ 方法1; 方法2; … public void run(){ // other code… } 屬性1; 屬性2; … }
class hello implements Runnable { public hello() { } public hello(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "運行 " + i); } } public static void main(String[] args) { hello h1=new hello("線程A"); Thread demo= new Thread(h1); hello h2=new hello("線程B"); Thread demo1=new Thread(h2); demo.start(); demo1.start(); } private String name; }
【可能的運行結果】:
線程A運行 0
線程B運行 0
線程B運行 1
線程B運行 2
線程B運行 3
線程B運行 4
線程A運行 1
線程A運行 2
線程A運行 3
線程A運行 4
盡量去實現Runnable接口