Java教程

Java run()方法

如果线程是使用单独的Runnable对象构造的,则调用线程类的 run()方法方法不执行任何操作并返回。调用run()方法时,将执行run()方法中指定的代码。您可以多次调用run()方法。
可以使用start()方法或通过调用run()方法本身来调用run()方法。但是,当您使用run()方法调用自身时,会产生问题。

返回

It does not return any value.

示例1: 使用start()方法调用run()方法

public class RunExp1 implements Runnable
{
    public void run()
    {
        System.out.println("Thread is running...");
    }
    public static void main(String args[])
    {
        RunExp1 r1=new RunExp1();
        Thread t1 =new Thread(r1);
        // this will call run() method
        t1.start();
    }
}
输出:
Thread is running...

示例2: 使用run()方法本身调用run()方法

public class RunExp2 extends Thread
{
    public void run()
    {
        System.out.println("running...");
    }
    public static void main(String args[])
    {
        RunExp2 t1=new RunExp2 ();
        // It does not start a separate call stack
        t1.run();
    }
}
输出:
running...
在这种情况下,它转到当前调用堆栈,而不是新调用堆栈的开头。

示例3: 调用run()方法不止一个时间

public class RunExp3 extends Thread
{
    public void run()
    {
        for(int i=1;i<6;i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(InterruptedException e){
                System.out.println(e);
            }
            System.out.println(i);
        }
    }
    public static void main(String args[])
    {
        RunExp3 t1=new RunExp3();
        RunExp3 t2=new RunExp3();
        t1.run();
        t2.run();
    }
}
输出:
1
2
3
4
5
1
2
3
4
5
在上面的示例3中,没有内容切换,因为在这里t1和t2被视为普通对象而不是线程对象。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4