我是新來的多線程,我只是試圖通過使用線程打印14000大小字符串Arraylist實踐。我並沒有考慮效率,甚至對這個問題也沒有用處;我只想了解線程概念。你如何修復線程連接()卡住
我的輸出已經非常錯誤,我嘗試了各種同步和其他失敗的嘗試。我目前遇到了一個名爲join的工具,但是我的程序沒有退出並保持運行。我調試了代碼,程序只是停留在第一個線程連接上,我想不出任何理由或解決方案來解決問題。
我接近這個問題的方式是創建4個線程來分割打印任務。然後我會等到所有線程都完成並在關閉輸出文件之前使用連接權限。
public class Threadprinting implements Runnable{
private static List<String> list;
private Thread T1,T2,T3,T4;
public void printinput(List<String> store){
list=new ArrayList<String>(store);
Threadprinting threadprinting=new Threadprinting();
Threadprinting.generatethreads();
}
public void generatethreads() {
T1=new Thread(this,"t1");
T1.start();
T2=new Thread(this,"t2");
T2.start();
T3=new Thread(this,"t3");
T3.start();
T4=new Thread(this,"t4");
T4.start();
}
public void run(){
try {
PrintWriter out = new PrintWriter(new FileWriter("Output.txt"));
switch (Thread.currentThread().getName()) {
case "t1":
System.out.println("Thread "+ Thread.currentThread().getName() + " is running");
for (int i = 0; i < list.size()/4; i++) {
out.println((list.get(i)));
}
break;
case "t2":
System.out.println("Thread "+ Thread.currentThread().getName() + " is running");
for (int i = list.size()/4; i < list.size()/2; i++) {
out.println((list.get(i)));
}
break;
case "t3":
System.out.println("Thread "+Thread.currentThread().getName()+" is running");
for (int i = list.size()/2; i < list.size()/4+list.size()/2; i++) {
out.println((list.get(i)));
}
break;
case "t4":
System.out.println("Thread "+Thread.currentThread().getName()+" is running");
for (int i = list.size()/4+list.size()/2; i < list.size(); i++) {
out.println((list.get(i)));
}
break;
default:
System.out.println("filler");
break;
}
jointhreads();
out.close();
}
catch(IOException e){
System.out.println("problem came from here");
}
}
具體來說:
private void jointhreads() {
try {
T1.join();
T2.join();
T3.join();
T4.join();
} catch (InterruptedException e) {
System.out.println("the joins failed");
}
}
}
程序無法終止,並根據調試器在T1.join保持運行。
你在T1中,你做了一個T1.join(),是你的問題嗎? – fluminis