我有一個類,它實現Runnable
接口。我想創建該類多線程,我發現兩種方法用於創建多線程:在java中創建Multithread的正確方法?
class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
}
}
1.首先方法:
public class TestThreads {
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
foo.start();
bar.start();
bat.start();
}
}
2.second方法:
public class TestThreads
{
public static void main (String [] args)
{
Thread[] worker=new Thread[3];
MyRunnable[] r = new MyRunnable[3];
for(int i=0;i<3;i++)
{
r[i] = new MyRunnable();
worker[i]=new Thread(r[i]);
worker[i].start();
}
}
}
哪一個是最好的使用方法,兩者有什麼區別?
Regards
如果Runnable沒有狀態(無實例變量),則不需要Runnable的三個實例。除此之外,使用ExecutorService,不要創建自己的線程。 – Thilo