请帮助我了解如何通过调用线程类的 start 方法来调用 run 方法。
问问题
1957 次
4 回答
4
该start()
方法启动一个新的执行线程,并安排事情以便新的执行线程调用该run()
方法。确切的机制是特定于操作系统的。
于 2013-02-28T07:09:03.643 回答
2
我建议查看java.lang.Thread.start()
方法的源代码。它是一个同步方法,依次调用私有本机方法,然后操作系统特定的线程机制接管(最终调用当前对象的 run() 方法)
于 2013-02-28T07:13:55.670 回答
1
来自文档
公共无效开始()
使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
结果是两个线程同时运行:当前线程(从对 start 方法的调用返回)和另一个线程(执行其 run 方法)。
于 2013-02-28T07:10:58.647 回答
0
线程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();
}
}
于 2013-02-28T07:34:17.723 回答