通过实现runnable接口创建线程

时间:2014-10-28 06:08:54

标签: java multithreading

可以通过将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 个答案:

答案 0 :(得分: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. 

答案 1 :(得分:2)

如果只运行单个线程,则两种方式完全相同。这取决于: 1.是否要重新使用runnable 2.是否需要返回runnable中的属性。

仅当您要执行Fire和Forget时才使用方法2.