扩展java.lang.Thread类
运行结果:
main 线程运行开始!
main 线程运行结束!
A 线程运行开始!
0 A
1 A
B 线程运行开始!
2 A
0 B
3 A
4 A
1 B
5 A
6 A
7 A
8 A
9 A
A 线程运行结束!
2 B
3 B
4 B
5 B
6 B
7 B
8 B
9 B
B 线程运行结束!
说明:
程序启动运行main时候,java虚拟机启动一个进程,主线程main在main()调用时候被创建。随着调用MitiSay的两个对象的start方法,另外两个线程也启动了,这样,整个应用就在多线程下运行。
在一个方法中调用Thread.currentThread().getName()方法,可以获取当前线程的名字。在mian方法中调用该方法,获取的是主线程的名字。
注意:start()方法的调用后并不是立即执行多线程代码,而是使得该线程变为可运行态(Runnable),什么时候运行是由操作系统决定的。
从程序运行的结果可以发现,多线程程序是乱序执行。因此,只有乱序执行的代码才有必要设计为多线程。
Thread.sleep()方法调用目的是不让当前线程独自霸占该进程所获取的CPU资源,以留出一定时间给其他线程执行的机会。
实际上所有的多线程代码执行顺序都是不确定的,每次执行的结果都是随机的。
1 public class TestMitiThread {
2
3 public static void main(String[] rags) {
4
5 System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
6
7 new MitiSay("A").start();
8
9 new MitiSay("B").start();
10
11 System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
12
13 }
14
15 }
16
17 class MitiSay extends Thread {
18
19 public MitiSay(String threadName) {
20
21 super(threadName);
22
23 }
24
25 public void run() {
26
27 System.out.println(getName() + " 线程运行开始!");
28
29 for (int i = 0; i < 10; i++) {
30
31 System.out.println(i + " " + getName());
32
33 try {
34
35 sleep((int) Math.random() * 10);
36
37 } catch (InterruptedException e) {
38
39 e.printStackTrace();
40
41 }
42
43 }
44
45 System.out.println(getName() + " 线程运行结束!");
46
47 }
48
49 }
50
51
2
3 public static void main(String[] rags) {
4
5 System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
6
7 new MitiSay("A").start();
8
9 new MitiSay("B").start();
10
11 System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
12
13 }
14
15 }
16
17 class MitiSay extends Thread {
18
19 public MitiSay(String threadName) {
20
21 super(threadName);
22
23 }
24
25 public void run() {
26
27 System.out.println(getName() + " 线程运行开始!");
28
29 for (int i = 0; i < 10; i++) {
30
31 System.out.println(i + " " + getName());
32
33 try {
34
35 sleep((int) Math.random() * 10);
36
37 } catch (InterruptedException e) {
38
39 e.printStackTrace();
40
41 }
42
43 }
44
45 System.out.println(getName() + " 线程运行结束!");
46
47 }
48
49 }
50
51