0
這裏儲值我寫了一個代碼,使用多線程,但結果是出乎意料的獲得來自用戶名多線程來獲取和從用戶
輸入
as as dd ff ee ew qq ff hh tt
輸出:
as ff ew hh tt qq ff null null null
最後顯示三個空字符。我創建了兩個線程併爲每個線程分配了五個迭代。這裏
package Pack;
import java.util.Scanner;
public class add implements Runnable
{
int value[];
public add(int[] value)
{
this.value=value;
}
public void run()
{
@SuppressWarnings("resource")
Scanner in= new Scanner(System.in);
for(int i:value)
{
Thread1.str[i]=in.nextLine();
}
}
}
package Pack;
public class Thread1 {
public static String[] str= new String[10];
public static void main(String[] args) throws InterruptedException
{
Thread[] th= new Thread[2];
add a[]=new add[2];
int num[]={0,1,2,3,4,5,6,7,8,9};
for(int i=0;i<2;i++)
{
int part[]= new int[5];
for(int j=0;j<5;j++)
part[j]= num[i*2+j];
a[i]= new add(part);
th[i]= new Thread(a[i]);
}
for(Thread th1 : th)
{
System.out.println(th1.getName());
th1.start();
}
for(Thread th1 : th)
th1.join();
for(String num1:str)
{
System.out.println(num1);
}
}
}
請解釋你的程序應該做什麼以及期望的輸出是什麼。還要解釋線程應該在這裏做什麼。 – RealSkeptic
這裏我試圖從用戶那裏獲得10個名字,將它存儲在變量中並使用多線程打印。所以我創建了兩個線程來執行五次迭代。我已經給出了上面的輸入,但是在打印時顯示&values和三個null。 – Magneto
歡迎來到Stack Overflow!請參考[遊覽](http://stackoverflow.com/tour),環顧四周,閱讀[幫助中心](http://stackoverflow.com/help),特別是[我該如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)和[我可以問什麼問題?](http://stackoverflow.com/help/on-topic)。請閱讀(並遵循) [Java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html) –