當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Thread 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被視為普通對象而不是線程對象。







相關用法


注:本文由純淨天空篩選整理自 Java Thread run() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。