代码1
main 方法调用 thread.run(),不会出现“主线程”。因为调用thread.run() 没有另起线程而是在main所在线程直接调用thread.run(),thread.run()不执行完,后面的代码就不会继续执行,所以这里不会出现“主线程”。
public class NewThread implements Runnable {
@Override
public void run() {
while (true){
System.out.println("自定义线程");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new NewThread());
thread.run();
while (true){
System.out.println("主线程");
}
}
}
代码2
main 方法调用 thread.start(),会出现“主线程”和“自定义线程”。因为调用thread.start() 会另起一个线程来执行run() ,它和main所在线程是两条线程,这两条线程会分别执行“自定义线程”和“主线程”。
public class NewThread implements Runnable {
@Override
public void run() {
while (true){
System.out.println("自定义线程");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new NewThread());
thread.start();
while (true){
System.out.println("主线程");
}
}
}