2013-07-05 20 views
-7

在java中啓動一個線程,類應該實現它的run方法JAVA:如何啓動多個線程在1類

public class MyClass implements Runnable { 
    run() { 
     // some stuff 
    } 

    public static void main(String []args) { 
     Thread myThread = new Thread(this); 
     myThread.start(); 
    } 
} 

的問題是,我該怎麼辦,如果我要開始在幾個不同的線程我的課。我知道1種方法 - 爲每個線程函數實現類,但我認爲應該有更簡單的方法。

+1

怎麼樣一個循環:

public class MyClass implements Runnable{ public MyClass(){} public void run(){ // some operation here } } 
在MainClass你就可以開始儘可能多線程作爲

? – 2013-07-05 11:00:11

+0

你能解釋爲什麼你想開始許多聽起來沒有任何目的的線程。 –

+0

你應該看看:http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html –

回答

2

此代碼創建並啓動四個線程:

public class MyClass implements Runnable { 
    run() { 
     // some stuff 
    } 

    public static void main(String []args) { 
     MyClass myClass = new MyClass(); 
     Thread t1 = new Thread(myClass); 
     Thread t2 = new Thread(myClass); 
     Thread t3 = new Thread(myClass); 
     Thread t4 = new Thread(myClass); 
     t1.start(); 
     t2.start(); 
     t3.start(); 
     t4.start(); 
    } 
} 
+0

不應該使用'MyClass'的不同實例爲每個「線程」? – Dahaka

+0

要在所有線程之間進行同步,所有線程必須屬於同一個對象。如果您使用不同的對象創建線程,則它們不會同步。 –

+0

您可以使用相同的實例。但是,如果您從多個線程修改此實例的字段,則應該小心。 – Bitman

0

假設你的線程類如下。

MyClass obj1 = new MyClass(); 
    MyClass obj2 = new MyClass(); 
    Thread t1 = new Thread(obj1); 
    Thread t2 = new Thread(obj2); 
    t1.start(); 
    t2.start();