java 多線程(轉)

http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html

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接口:

 

大致框架是:

1
2
3
4
5
6
7
8
9
10
11
12
class 類名 implements Runnable{
方法1;
方法2
public void run(){
// other code…
}
屬性1
屬性2
 
}

來先看一個小例子吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * @author Rollen-Holt 實現Runnable接口
 * */
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

發佈了28 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章