java 线程中run 和start方法
程序员文章站
2024-01-26 22:02:16
...
Java线程中run和start方法
1.两者的区别说明
start()方法:start的作用是开启一个新线程执行新开启线程的run()方法,start方法不能被重复调用
run()方法:run方法的就相当于一个普通的成员方法,直接调用在当前线程中处理run方法的主体,可以重复调用
2.run方法和start方法示例
public static void main(String args[]) {
Thread mythread=new ThreadDemo("mythread");
mythread.run();
mythread.run();
mythread.start();}
public class ThreadDemo extends Thread{
public ThreadDemo(String name) {
super(name);
}
public void run(){
System.out.println(Thread.currentThread().getName()+" is running");
}
}
运行结果:
main is running
main is running
mythread is running
可以看到,当直接调用run方法时时在当前线程执行run方法,当前线程的名称是main,此时可以进行多次调用
当调用start方法时,将新开启一个线程执行run方法的主体,此时如果重复调用则会出现以下异常信息
Exception in thread "main" mythread is running
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:705)
at com.test.demo.thread.ThreadTest.main(ThreadTest.java:13)
我们查看Thread类的源码
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
从以上红色代码部分不难发现,当threadStatus的状态不为0时都抛出 IllegalThreadStateException()异常,而从注释部分我们可以看出只有当线程的状态为新建 (NEW)时,其threadStatus的值才为0 因此当连续调用线程的start方法则会抛出上面的异常。关于线程的几种状态我们将在下一张详细讲述。