Como a execução do thread é iniciada?
Eu estava procurando um pequeno exemplo em Threads.Para criar Threads, podemos fazer de duas maneiras, implementandoRunnable
interface ou estendendo o Thread.I usei a primeira maneira
package test;
public class test implements Runnable{
public static void main(String args[])
{
test t=new test();
t.run();Thread th=Thread.currentThread();
th.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("hi");
}
}
Minha dúvida é quando estamos ligandoth.start();
entãorun()
é chamado.Eu quero saber how.I pensei internamente lástart()
pode estar chamandorun()
então eu olhei na documentação da classe Thread
O seguinte é ostart()
declaração na classe Thread
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 */
}
}
}
Como você pode ver por dentrostart()
,run()
não é chamado, mas quando estamos chamandoth.start()
então substitui automaticamenterun()
alguém pode, por favor, lançar alguma luz neste