在java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable接口。
對於直接繼承Thread的類來說,代碼大致框架是:
1
2
3
4
5
6
7
8
9
10
11
12
|
class 類名
extends Thread{ 方法 1 ; 方法 2 ; … public void run(){ //
other code… } 屬性 1 ; 屬性 2 ; … }
public static void main(String[]
args) { hello
h1= new hello( "A" ); hello
h2= new hello( "B" ); h1.start(); h2.start(); }
通過實現Runnable接口:
大致框架是:
來先看一個小例子吧:
【可能的運行結果】: 線程A運行 0 線程B運行 0 線程B運行 1 線程B運行 2 線程B運行 3 線程B運行 4 線程A運行 1 線程A運行 2 線程A運行 3 線程A運行 4 |