繁体   English   中英

线程类中start方法如何调用子类的run方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM