在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。
对于直接继承Thread的类来说,代码大致框架是:
class
类名
extends
Thread{
方法
1
;
方法
2
;
…
public
void
run(){
// other code…
}
属性
1
;
属性
2
;
…
}
/**
* @author Rollen-Holt 继承Thread类,直接调用run方法
* */
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.run();
h2.run();
}
private
String name;
}
【运行结果】:
A运行 0
A运行 1
A运行 2
A运行 3
A运行 4
B运行 0
我们会发现这些都是顺序执行的,说明我们的调用方法不对,应该调用的是start()方法。
当我们把上面的主函数修改为如下所示的时候:
public
static
void
然后运行程序,输出的可能的结果如下:
A运行 0
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4
A运行 1
A运行 2
A运行 3
A运行 4
虽然我们在这里调用的是start()方法,但是实际上调用的还是run()方法的主体。
那么:为什么我们不能直接调用run()方法呢?
我的理解是:线程的运行需要本地操作系统的支持。
如果你查看start的源代码的时候
main(String[] args) {
hello h1=
new
hello(
"A"
);
hello h2=
new
hello(
"B"
);
h1.start();
h2.start();
}
B运行 1
B运行 2
B运行 3
B运行 4