Thread.run or Thread.start
Common Pitfall: Calling run() Instead of start()
When creating and starting a thread a common mistake is to call the run() method of the Thread instead of start(), like this:
Thread newThread = new Thread(MyRunnable());
newThread.run(); //should be start();
At first you may not notice anything because the Runnable’s run() method is executed like you expected. However, it is NOT executed by the new thread you just created. Instead the run() method is executed by the thread that created the thread. In other words, the thread that executed the above two lines of code. To have the run() method of the MyRunnable instance called by the new created thread, newThread, you MUST call the newThread.start() method.
示例:
TestRunnable.java
public class TestRunnable implements Runnable {
private StopWatch stopWatch;
public TestRunnable() {
stopWatch = new StopWatch();
}
@Override
public void run() {
stopWatch.start();
System.out.println("TestRunnable start");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("TestRunnable end %s", stopWatch.getTime()));
}
}
Thread.start()方法
public class TestRunnableMain {
public static void main(String[] args) {
System.out.println("TestRunnableMain start");
TestRunnable testRunnable = new TestRunnable();
Thread thread = new Thread(testRunnable);
thread.start();
System.out.println("TestRunnableMain end");
}
}
执行结果:
TestRunnableMain start
TestRunnableMain end
TestRunnable start
TestRunnable end 5012
Thread.run()方法
public class TestRunnableMain {
public static void main(String[] args) {
System.out.println("TestRunnableMain start");
TestRunnable testRunnable = new TestRunnable();
Thread thread = new Thread(testRunnable);
thread.run();
System.out.println("TestRunnableMain end");
}
}
执行结果:
TestRunnableMain start
TestRunnable start
TestRunnable end 5009
TestRunnableMain end
http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html
还没有评论,来说两句吧...