start() and run()两者有什么不同?
作者:互联网
- 调用start()时,会新建一个线程,然后会在新建的线程里调用run();
而调用run()方法时,则不会新建一个线程,而是会在当前线程下执行run(),其实就是当作了一个普通方法;
public class Runner implements Runnable{
@Override
public void run() {
System.out.println("CurrentThread Name:"+Thread.currentThread().getName());
System.out.println("invoke run method");
}
}
public class Starter implements Runnable{
@Override
public void run() {
System.out.println("CurrentThread Name:"+Thread.currentThread().getName());
System.out.println("invoke start method");
}
}
public class TestStarterAndRunner {
public static void main(String[] args) {
Starter starter = new Starter();
Runner runner = new Runner();
Thread starterThread = new Thread(starter);
Thread runnerThread = new Thread(runner);
starterThread.start();
runnerThread.run();
}
}
===============================================
CurrentThread Name:main
invoke run method
CurrentThread Name:Thread-0
invoke start method
- start()不能被多次(只能一次)调用,在同意对象里面,否则会抛出java.lang.IllegalThreadStateException;
run()则可以被多次调用
public class TestStarterAndRunner {
public static void main(String[] args) {
Starter starter = new Starter();
Thread starterThread = new Thread(starter);
starterThread.start();
starterThread.start();
}
}
================================================
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:710)
at com.rookie.concurrent.TestStarterAndRunner.main(TestStarterAndRunner.java:15)
CurrentThread Name:Thread-0
invoke start method
public class TestStarterAndRunner {
public static void main(String[] args) {
Runner runner = new Runner();
Thread runnerThread = new Thread(runner);
runnerThread.run();
runnerThread.run();
}
}
===============================================
CurrentThread Name:main
invoke run method
CurrentThread Name:main
invoke run method
标签:run,Thread,两者,start,new,main,public 来源: https://www.cnblogs.com/masker99/p/16139581.html