我有以下代碼線程和中斷
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 f, l;
private Thread greetings1, greetings;
public static void main(String[] args) {
String[] elements = { "Tim", "Fred", "Jeff", "Scott" };
Threads t = new Threads();
for (String e : elements) {
t.threadL(e);
t.threadR(e);
}
for (int index = 0; index < t.threadList.size(); index++) {
// blank at the moment
}
}
public void threadR(String f) {
greetings = new Thread(f);
Thread greetingsFromFred = new Thread(greetings) {
@Override
public void run() {
for (int i = 1; i < 5; i++) {
try {
System.out.println("Main Thread: " + i + " " + f);
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
};
greetingsFromFred.start();
}
public List<Thread> threadL(String l) {
greetings1 = new Thread(this);
this.l = l;
greetings1.start();
threadList.add(greetings1);
return (threadList);
}
@Override
public void run() {
greetings.interrupt(); // interrupt greetings thread here <-------
System.out.println("Greetings from " + l + "! threadL");
}
}
當線程1運行我想從運行中斷threadR並因此導致
System.out.println("Main thread interrupted.");
從threadR
我有印刷在我的代碼高亮顯示,其中中斷應該發生
greetings.interrupt(); //interrupt greetings thread here <-------
爲什麼中斷不能正常工作?
請修正您的代碼中的縮進;目前它是無法讀取的。 –
你的意思是「中斷不能像目前那樣工作」? –
「擴展了Thread implements Runnable」我建議你在其中之一中進行選擇。 – MeetTitan