![](/img/trans.png)
[英]how does start() method of thread class call run() method of child class when it implements thread class
[英]Thread class how start method calls the run method of sub class
請幫助我了解如何通過調用線程類的start方法來調用run方法。
start()
方法啟動一個新的執行線程,並進行安排,以便新的執行線程調用run()
方法。 確切的機制是特定於OS的。
我建議看一下java.lang.Thread.start()
方法的源代碼。 它是一個同步方法,該方法依次調用私有本機方法 ,然后由特定於操作系統的線程機制接管( 最終調用當前對象的run()方法 )
來自文檔
公共無效的開始()
使該線程開始執行; Java虛擬機將調用此線程的run方法。
結果是兩個線程同時運行:當前線程(從調用返回到start方法)和另一個線程(執行其run方法)。
線程start()
調用run()
是一個內部進程,而線程依賴於平台。
以下是Java開發人員說的話
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()
您確定不必為此擔心。 如果您正在尋找線程示例,這是一個
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.