请帮助我了解如何通过调用线程类的start方法来调用run方法。
答案 0 :(得分:4)
start()
方法启动一个新的执行线程,并安排一些事情,以便新的执行线程调用run()
方法。确切的机制是特定于操作系统的。
答案 1 :(得分:2)
我建议查看java.lang.Thread.start()
方法的源代码。它是一个同步方法,它反过来调用私有本机方法,然后操作系统特定的线程机制接管(最终调用当前对象的run()方法)
答案 2 :(得分:1)
来自docs
public void start()
使该线程开始执行; Java虚拟机调用此线程的run方法。
结果是两个线程同时运行:当前线程(从调用start方法返回)和另一个线程(执行其run方法)。
答案 3 :(得分: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();
}
}