一、线程的start()方法
start()方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码: 通过调用Thread类的start()方法来启动一个线程,这时此线程是处于就绪状态,并没有运行。然后通过此Thread类调用方法run()来完成其运行操作的,这里方法run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程终止,而CPU再运行其它线程。
public class TestThread implements Runnable{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
public static void main(String[] args) {
for(int i=0;i<2;i++){
TestThread testThread=new TestThread();
Thread thread=new Thread(testThread);
System.out.println("[线程"+(i+1)+"]正在启动!");
thread.start();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
控制台输出:
[线程1]正在启动!
[线程2]正在启动!
Thread-0---1
Thread-0---2
Thread-0---3
Thread-1---1
Thread-1---2
Thread-1---3
1
2
3
4
5
6
7
8
二、线程的run()方法
run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码: 而如果直接用run方法,这只是调用一个方法而已,程序中依然只有主线程–这一个线程,其程序执行路径还是只有一条,这样就没有达到写线程的目的。
public class TestThread implements Runnable{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
public static void main(String[] args) {
for(int i=0;i<2;i++){
TestThread testThread=new TestThread();
Thread thread=new Thread(testThread);
System.out.println("[线程"+(i+1)+"]正在启动!");
thread.run();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
控制台输出:
[线程1]正在启动!
main---1
main---2
main---3
[线程2]正在启动!
main---1
main---2
main---3
1
2
3
4
5
6
7
8
三、线程的join方法
join()方法的功能:等该线程执行结束才会向下执行
public class TestThread implements Runnable{
public void run(){
for(int i=1;i<=3;i++){
System.out.println(Thread.currentThread().getName()+"---"+i);
}
}
public static void main(String[] args) {
for(int i=0;i<2;i++){
TestThread testThread=new TestThread();
Thread thread=new Thread(testThread);
System.out.println("[线程"+(i+1)+"]正在启动!");
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
控制台输出:
[线程1]正在启动!
Thread-0---1
Thread-0---2
Thread-0---3
[线程2]正在启动!
Thread-1---1
Thread-1---2
Thread-1---3
1
2
3
4
5
6
7
8
总结
调用start方法方可启动线程,而run方法只是thread的一个普通方法调用,还是在主线程里执行。这两个方法应该都比较熟悉,把需要并行处理的代码放在run()方法中,start()方法启动线程将自动调用 run()方法,这是由jvm的内存机制规定的。并且run()方法必须是public访问权限,返回值类型为void.。
---------------------
作者:码农云帆哥
来源:CSDN
原文:https://blog.csdn.net/sinat_27933301/article/details/79565259
版权声明:本文为博主原创文章,转载请附上博文链接!