2014-10-28 113 views
0

螺紋的螺紋可以通過實現Runnable作爲創建通過實現Runnable接口

public class Program implements Runnable{ 

public void run(){ 
    System.out.println("Thread in progress"); 
} 

public static void main(string args[]){ 
    Program p1 = new Program(); 
    new Thread(p1).start(); 

    //we can also use 

    (new Thread(new Program())).start(); 
} 

} 

是一種方法優於其他產生的呢?

回答

2
Program p1 = new Program(); 
    new Thread(p1).start(); // this thread and the next thread share the same Runnable instance 
    // So, they share the instance level fields also. Thus either one of them can change the state of p1 
    new Thread(p1).start(); 
    //we can also use 

    (new Thread(new Program())).start(); 
    // This one creates a new instance of Program/ Runnable, thus does not share the same object. 
2

如果您只運行單個線程,兩種方式運行完全相同。取決於: 1.是否要重新使用可運行的 2.是否需要返回可運行內的屬性。

只有在您想要執行Fire And Forget時才使用方法2。