class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
// 最基本的创建线程的办法
public class Demo1 {
public static void main(String[] args) {
Thread t = new MyThread();
t.start(); // 会创建新线程
while (true){
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
运行上述代码后,我们可以通过控制台看到输出得结果是:有两个线程在执行,此时调用得是 t.start()
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
// 最基本的创建线程的办法
public class Demo1 {
public static void main(String[] args) {
Thread t = new MyThread();
t.run(); // 不会创建新线程
while (true){
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
而调用 t.run() 之后,此时控制台输出结果只有hello thread,此时因为并没有创建新的线程,所以当执行run()进入方法后,就开始死循环,由于只有一个main线程,所以就无法再执行打印hello main
下面总结下二者的区别:
- start()方法被用来启动新创建的线程,而且start()内部调用了run()方法,这和直接调用run()方法的效果不一样。当你调用run()方法的时候,只会是在原来的线程中调用,没有新的线程启动,start()方法才会启动新线程。