线程run方法和start方法区别
package com.mc.testThread;
import java.util.Random;
public class MyThread extends Thread {
private String flag;
public MyThread(String flag) {
this.flag = flag;
}
@Override
public void run() {
System.out.println("我的线程开始工作了..." + flag);
String name2 = Thread.currentThread().getName();
for (int i = 0; i < 20; i++) {
try {
Random random = new Random();
System.out.println("线程" + name2 + "............." + flag);
Thread.sleep(random.nextInt(10) * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
/**
* thread.run()方法只是单纯的类方法调用,用的是同一个主线程main
* thread.start()方法是开启另外一个线程来进行调用的
* start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法,这里方法
* run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。
*/
Thread thread = new MyThread("a");
Thread thread1 = new MyThread("b");
// thread.start();
// thread1.start();
thread.run();
thread1.run();
}
}
可以看到,调用start的方法的时候,是直接轮询开启两个线程
我的线程开始工作了...a
我的线程开始工作了...b
线程Thread-0.............a
线程Thread-1.............b
线程Thread-1.............b
线程Thread-0.............a
线程Thread-0.............a
线程Thread-1.............b
线程Thread-0.............a
线程Thread-1.............b
线程Thread-0.............a
线程Thread-1.............b
线程Thread-0.............a
线程Thread-0.............a
线程Thread-1.............b
线程Thread-0.............a
线程Thread-1.............b
单独调用 thread.run()方法的时候,线程只有一个main线程,执行完a后才执行b
我的线程开始工作了...a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
线程main.............a
我的线程开始工作了...b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b
线程main.............b