Reputation: 19
Please help me out to understand how does run method gets called by calling start method of thread class.
Upvotes: 1
Views: 1981
Reputation: 23025
Thread start()
call run()
is an internal process, while threading is platform dependent.
Following is what Java developers say
java.lang.Thread
public synchronized void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Throws:
IllegalThreadStateException - if the thread was already started.
See Also:
Thread.run(), Thread.stop()
You sure don't have to worry about this. If you are seeking for an thread example, here is one
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ThreadEx extends JFrame
{
private JLabel numTxt;
private JButton click;
private Thread t = new Thread(new Thread1());
public ThreadEx()
{
numTxt = new JLabel();
click = new JButton("Start");
click.addActionListener(new ButtonAction());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
centerPanel.add(numTxt);
centerPanel.add(click);
this.add(centerPanel,"Center");
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class Thread1 implements Runnable
{
@Override
public void run()
{
try
{
for(int i=0;i<100;i++)
{
numTxt.setText(String.valueOf(i));
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private class ButtonAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
t.start();
}
}
public static void main(String[]args)
{
new ThreadEx();
}
}
Upvotes: 0
Reputation: 17903
I would suggest to look at the source code of java.lang.Thread.start()
method. Its a synchronized method which in turn calls private native method and then the OS specific threading mechanism takes over (which eventually calls the run() method of the current object)
Upvotes: 2
Reputation: 3407
From docs
public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
Upvotes: 1
Reputation: 500367
The start()
method starts a new thread of execution, and arranges things so that the new thread of execution invokes the run()
method. The exact mechanics are OS-specific.
Upvotes: 4