多线程之Runnable

来源:互联网 发布:桌面美化软件 编辑:程序博客网 时间:2024/06/06 03:50

由于Java只能单继承,所以有时候我们不能通过继承extends来开启一个线程,这个时候我们就可以通过implements Runnable来开启一个线程,实验代码如下:

package learnIng;public class Thread2 implements Runnable{    public void run() {        for (int i = 0; i < 50; i++) {            System.out.println(i);        }    }    public static void main(String[] args) throws InterruptedException {        Thread2 lt = new Thread2();        Thread t1=new Thread(lt);        t1.start();//      t1.join();        Thread2 lt1 = new Thread2();        Thread t2=new Thread(lt1);        t2.start();    }}

实验结果如下:
0
1
2
3
4
5
6
7
8
9
0
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
我们也可以通过使用函数体来开启线程,这样避免implements Runnable.实验代码如下:

package learnIng;public class ThreadRunnable {    void java_thread() {        Thread t = new Thread(new Runnable() {            public void run() {                for (int i = 0; i < 50; i++) {                    System.out.println(i);                }            }        });        t.start();    }    public static void main(String[] args) {        ThreadRunnable tr = new ThreadRunnable();        tr.java_thread();        ThreadRunnable tr1 = new ThreadRunnable();        tr1.java_thread();    }}

0
1
2
3
4
5
6
7
0
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

0 0
原创粉丝点击