首页 > 代码库 > Thread的run和start
Thread的run和start
class TestThread extends Thread{
public void run(){
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+"---is running");
}
}
}
public class Thread01 {
public static void main(String[] args) {
TestThread tt1 = new TestThread();
TestThread tt2 = new TestThread();
// tt1.run();
// tt2.run();
tt1.start();
tt2.start();
// new TestThread().start();
}
}
线程Thread中start()和run()的方法。
start()是实现并发的重点,run()不过是调用类TestThread中的run()方法。
使用start()时,结果为:
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
Thread-0---is running
Thread-1---is running
当调用run()时,结果为:
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
main---is running
启动一个新的线程不是直接调用子类的run方法,而是调用thread类的start方法,thread类的start方法将产生一个新的线程,并在新的线程上运行该thread类对象中的run方法。由于线程的代码段是在run方法中,那么该方法执行完以后,线程也就相应结束了。
Thread的run和start