Java Thread run()方法

如果線程是實現Runnable介面的,則調用Thread類的run()方法,否則此方法不執行任何操作並返回。 當run()方法調用時,將執行run()方法中指定的代碼。可以多次調用run()方法。

可以使用start()方法或通過調用run()方法本身來調用run()方法。 但是當使用run()方法調用自身時,它會產生問題。

示例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 中,沒有內容切換,因為這裏t1t2被視為普通對象而不是線程對象。


上一篇: Java Runtime類 下一篇:無