2015-12-30 119 views
-4

我可以讓我的方法threadR通過一個可運行的線程來運行,但我不能似乎得到線程1運行的線程,並從我的運行線程打印到控制檯線程擴展Thread

System.out.println("Greetings from Fred! threadL");

我做錯了什麼?

package threads; 

import java.util.ArrayList; 
import java.util.List; 

public class Threads extends Thread implements Runnable { 

private final List<Thread> threadList = new ArrayList<>(); 
private String e,l; 
private Thread greetings; 


public static void main(String[] args) { 

String[] elements = {"Tim","Fred"};  
Threads t = new Threads(); 
for (String e: elements) { 
t.threadL(e); 
t.threadR(e); 
} 



for(int index = 0;index<t.threadList.size();index++){ 
System.out.print(t.threadList.get(index).getName()+ " ID "+   t.threadList.get(index).getId()+"\n"); 

} 
} 



public List<Thread> threadL(String l) { 
Thread greetings1 = new Thread(l); 

greetings1.start(); 
threadList.add(greetings1); 
//System.out.print(greetings.getName()+"\n"); 
//System.out.print(greetings.getId()+"\n"); 
    return(threadList); 

} 
public List<Thread> threadR(String f) { 
greetings = new Thread(f); 
Thread greetingsFromFred = new Thread(greetings) { 
@Override 
public void run() { 
    System.out.println("Greetings from Fred! threadR"); 

} 
}; greetingsFromFred.start(); 

threadList.add(greetings); 
//System.out.print(greetings.getName()+"\n"); 
//System.out.print(greetings.getId()+"\n"); 
    return(threadList); 
} 

    public void run() { 
     System.out.println("Greetings from Fred! threadL"); //this is what wont run 
    } 
+0

審查代碼更容易,當它被格式化 – wero

+0

你創建過多線程...解釋你想達到什麼樣的,可能有更好的方法來做到這一點。 – CtrlAltDel

+0

@ CtrlAltDel我只創建了兩個額外的線程,一個叫做Tim和Fred,它在threadR方法下運行。然後我試圖在threadL方法下做同樣的事情,所以還有2個線程。除了主線程之外。我只是做一些實驗來更好地理解在表模型上執行的線程。 – Ingram

回答

2

當你傳遞一個字符串作爲唯一的參數new Thread(String);你實際上是設置線程名稱。你可能意味着通過一個Runnable的線程這樣

Thread greetings1 = new Thread(this); 

Thread Constructors

+0

是的,這是完全按照我想要的 - 我沒有發現,並不能認爲它出錯的地方 – Ingram